Program output is NaN instead of float - java

I am working on an exercise from a book, the exercise sounds like this:
Drivers are concerned with the mileage their automobiles get. One driver has kept track of several trips by recording the miles driven and gallons used for each tankful. Develop a Java application that will input the miles driven and gallons used (both as integers) for each trip. The program should calculate and display the miles per gallon obtained for each trip and print the combined miles per gallon obtained for all trips up to this point. All averaging calculations should produce floating-point results. Use class Scanner and sentinel-controlled repetition to obtain the data from the user.
Here is my code:
import java.util.Scanner;
public class consumption {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int miles = 0;
int gallons = 0;
int totalGallons = 0;
int totalMiles = 0;
float mpg = 0;
float totalAverage = 0;
System.out.println("Enter number of gallons or enter -1 to finish:");
gallons = in.nextInt();
while(gallons != -1)
{
gallons += totalGallons;
System.out.println("Enter the number of miles driven:");
miles = in.nextInt();
miles += totalMiles;
mpg = ((float)totalMiles/totalGallons);
System.out.printf("Total Miles per Gallon on this trip is %.2f\n", mpg);
System.out.println("Enter number of gallons:");
gallons = in.nextInt();
}
if(totalGallons!=0)
{
totalAverage = (float) totalMiles/totalGallons;
System.out.printf("Total consumption on all trips is %.2f\n", totalAverage);
}
else
System.out.println("You did not enter a valid gallon quantity\n");
}
}
For some reason, after I enter the sentinel (-1), the output shows NaN instead of the float number it should output.
Also, it does not calculate the totalAverage, not even showing NaN
This is the output:
Enter number of gallons or enter -1 to finish: 25
Enter the number of miles driven: 5
Total Miles per Gallon on this trip is NaN
Enter number of gallons: -1
You did not enter a valid gallon quantity
Process finished with exit code 0
Please help me :(

A NaN value typically arises when you divide zero by zero using floating operations. It is short for "not a number" and is used in some contexts where a computation produces a value that is nonsensical.
(NaN does not represent an infinite number! There is a different floating point value for that: INF).
The primitive operations that generate NaN values in Java are:
0.0 / 0.0
±INF / ±INF
0.0 * ±INF and ±INF * 0.0
INF + (-INF) and (-INF) + INF
INF - (INF) and (-INF) - (-INF)
Some java.lang.Math functions can also generate NaN values. For example, Math.sqrt(-1) produces a NaN.
Hint: take a look at where you are doing the calculation of mpg ... and how you are calculating the two values that the expression uses. Look at them carefully. (And check your lecture notes on what += actually does!)

Inside the while loop, you write the statements
gallons += totalGallons;
miles += totalMiles;
but totalGallons is initialized as 0 and its value never changes. The same is for totalMiles. Therefore the calculation for mpg
mpg = (float) totalMiles / totalGallons;
takes the form of
(float) 0/0;
which is infinity. In Java, infinity for float values is represented as Nan : Not a number. So just change the statements to
totalGallons += gallons;
totalMiles += miles;
EDIT
As the others have said, infinity is not Nan. There's a difference between when Java displays INF and when Nan. Refer to this question for more info: Difference between infinity and not-a-number.
Also, check #StephanC's answer on the cases where JAVA produces Nan.

Related

How do I fix the tax rate operation?

The goal is to provide the total sale, however, the tax rate is not calculating correctly since it keeps outputting 0.0.
import java.util.Scanner; //Required for axquiring user's input
public class salesTax {
public static void main(String[] args) {
int retailPrice; //Holds the retail price
int taxRate; //Holds sales tax rate
double salesTax; //Holds sales tax
double totalSale; //Holds total sale
//Scanner object to acquire user's input
Scanner input = new Scanner(System.in);
//Acquire user's retail price
System.out.println("What is the retail price of the item being purchased? ");
retailPrice = input.nextInt();
//Acquire user's sales tax rate
System.out.println("What is the sales tax rate? ");
taxRate = input.nextInt() / 100;
//Display the sales tax for the purchase
salesTax = retailPrice * taxRate; //Calculates the sales tax
System.out.println("The sales tax for the purchase is: " + salesTax);
//Display the total of the sale
totalSale = retailPrice + salesTax; //Calculate the total sale
System.out.println("The total of the sale is: " + totalSale);
}
}
Is there a way to fix the tax rate to produce accurate calculations, given that the tax rate is inputted by the user?
taxRate = input.nextInt() / 100;
This will give you 0 because you are dividing by an integer. You can take the number in as a float and divide by 100
float taxRate;
taxRate = input.nextFloat() / 100;
To calculate the tax rate you are reading an integer from System input and you are dividing it by 100 which gives an integer result, I think you are entering values less than 100. You need to read the values from the scanner as a float.
try this instead:
float taxRate;
taxRate = input.nextFloat() / 100;
EDIT:
As mentioned in the comments the taxRate value is between 0 and 1, so you should declare the taxRate as float or double.
Your tax rate needs to be a double since you're dividing it by 100 and then assigning it taxRate. Since tax rate is an int, it will truncate the value leaving only the integer value.
If taxRate = 7 and then you divide it by 100, you get 0.07. Since taxRate is an Integer value, when Java sees said 0.07 it will get rid of the decimal and only leave the whole number. Therefore, say taxRate = 3.9999, since taxRate is an int, it will truncate the value leaving 3. To fix this, change taxRate to a double.
Also, you need to read taxRate as a double value. To read a double value using Scanner, it will be taxRate = input.nextDouble() / 100;

Calculating Interest Rate for Java Assignment

I am brand new to Java and taking a programming course and really stuck on a particular assignment. I am trying to write a program that can compute the interest on the next monthly mortgage payment. The program needs to read the balance and APR from the console. I also need to put a check in place to make sure that the inputs of balance and the interest rate are not negative. We were also given the formula for (Interest = balance x (annualInterestRate / 1200))
UPDATE: I did the calculation and it seems to be working correctly. How would I put the check in place to make sure that the input of balance and interest is not negative?
import java.util.Scanner;
class assignment1{
public static void main(String[] args) {
float r, m;
Scanner s = new Scanner(System.in);
//System.out.println("Enter Monthly Payment and APR");
// txt
System.out.println("Enter Monthly Balance : ");
m = s.nextFloat();
//int balance = s.nextInt();
System.out.print("Enter the Interest Rate : ");
r = s.nextFloat();
//int interest = s.nextInt();
float rm;
rm = (m * (r / 1200));
// Output input by user
System.out.println("Interest on next monthly mortgage payment: " + rm);
//System.out.println("APR: " + interest);
}
}
Check out Arithmetic Operators in Java.
Something along the lines of "Interest = balance x (annualInterestRate / 1200)" would look very similar in Java code.
It would be something like:
int interestOnNextPayment = balance * (interest / 1200);
To verify that the answer is not negative, you'll want to use the comparison operators. These operators are: <, <=, >, and >=. You can learn more about them here.
For your particular example, you'd want to do something like this:
if(balance < 0 || interest < 0) {
System.out.println("Invalid input!");
}
This snippet will first check to see if balance is less than zero, then check to see if interest is less than zero (it works left to right). If either of those expressions are true, then it will run the code inside the if statement.

Calculating Interest (Java), the program should print the projected account balance after an arbitrary numbers of years

Please help me. Basically the program should Ask the user to input a number representing the initial balance of a savings account. Assign this number to a double variable called balance.
Ask for a number representing the yearly rate of interest (in percent) on the account. Divide this number by 100.0 and assign it to a double variable called rate. I have to use a loop to update the balance as it changes year by year. I am stuck on that part. Here is the code I have so far :
public static void calcInterest(){
System.out.println("Please enter the account balance : ");
System.out.println("Please enter the annual interest rate : ");
System.out.println("Please enter the number of years : ");
Scanner input = new Scanner (System.in);
double balance = input.nextDouble();
double y = input.nextDouble();
double rate = (y/100);
int years = input.nextInt();
}
There's no good reason to use a loop in this case, but I guess it's for learning purposes.
You can make a loop that calculates the new balance a year at a time like this:
for(int i = years; i > 0; i--)
balance = balance * y;
Alternatively use Math.pow(this follows the formula startvalue * rate of change^time = result):
balance = balance * Math.pow(y, years);

Need help calculating percentages for value

I'm having a little trouble writing a program that I was instructed to do as an assignment.
I'm just curious as to how I calculate a percentage for each value that is entered by the user. I'm having a little trouble trying to find the right way to word this so that it is readable and can be interpreted by Java properly.
My objective is to calculate each individual percentage for the amount of grams in fat, carbs and protein and display it on the screen. I'm not asking for someone to do the assignment for me, I'm just in need of a little guidance.
//local constants
//local variables
int carb; // amount of carbs entered by user
int fat; // amount of fat entered by user
int pro; // amount of protein entered by user
int sum; // sum of three numbers
//myLib = new Library();
/******************** Start main method *****************/
//Prompt user for amount of carbohydrates
System.out.print("Please enter the amount of carbohydrates: ");
carb = Keyboard.readInt();
//Prompt user for amount of fat
System.out.print("Please enter the amount of fat: ");
fat = Keyboard.readInt();
//Prompt user for amount of protein
System.out.print("Please enter amount of protein: ");
pro = Keyboard.readInt();
//Calculate the sum of the three numbers
sum = carb + fat + pro;
As Raman stated, it's relatively easy to calculate percentage now that you have the sum neatly stored in one variable
double carbPercent = ((double)carb / sum) * 100
double fatPercent = ((double)fat / sum) * 100
double proteinPercent = ((double)pro / sum) * 100

My division statement keeps coming out to 0

I am trying to make a program to calculate mpg on a road trip. I have it all laid out but on every run I get 0.0 for my mpg. I could use some help. I had to make mpg and totalMpg floats so I could do floating point division, if that doesn't make sense say so.
package Gas;
import java.util.Scanner;
import static java.lang.System.out;
public class GasTest {
public static void main(String[] args) {
int gas;
int miles;
int trips;
float mpg;
float totalMpg = 0;
int tripCounter = 1;
Scanner input = new Scanner (System.in);
out.println("Please input number of trips");
trips = input.nextInt();
while (tripCounter <= trips){
out.println ("Input gallons of gas used");
gas = input.nextInt();
out.println("Input miles traveled on trip");
miles = input.nextInt();
mpg = (gas / miles) ;
out.println("Your MPG for this trip was " + mpg);
totalMpg = (mpg + totalMpg) / 2;
out.println("Your overall MPG for all trips is " + totalMpg);
tripCounter++;
}
}
}
Cast gas to float in the below expression , if you don't want to declare gas as float.
This way you can take advantage of Widening Primitive Conversion, as mentioned in JLS.
mpg = ((float)gas / miles) ;
If miles is greater than gas, as both of them are int, the result will be 0, which will be stored as 0.0 when assigned to the float variable mpg.
You probably should declare them as float or cast gas when computing :
mpg = ((float)gas) / miles ;

Categories