My division statement keeps coming out to 0 - java

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 ;

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;

How to do an array in a loop

I am making an investment calculator.
So I will be doing a math problem and I want to loop it through each array and there will be 12 of them.
So let's say I am going to invest $1000 with a rate return of 4.5%.
So I will need to do 1000 * 0.045 + 1000 = 1,045 that equals one month. Then I need to do 1,045 * 0.045 + 1,045 = 1,092 that would equal the second month and how would I have it go through a loop like that?
Would I use a for loop? or?
This is what I have so far maybe you'll get it better by reading it. But I still need to create a loop that would like the example I gave above.
public class SimpleInvestment {
static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
double [] num = new double [11];
printWelcome();
double investTotal = getInvestAmount();
double rateTotal = getRate();
}
public static void printWelcome()
{
System.out.println("Welcome to the Investment Calulator");
}
public static double getInvestAmount()
{
double amountInvest;
System.out.print("Hou much will you be investing? ");
amountInvest = input.nextDouble();
while (amountInvest <= 0)
{
System.out.println("Amount must be greater than 0. Try again.");
System.out.print("How much will you be investing? ");
amountInvest = input.nextDouble();
}
return amountInvest;
}
public static double getRate()
{
double rate;
System.out.print("What will be the rate of return?");
rate = input.nextDouble();
while (rate < 0 )
{
System.out.println("Rate must be greater than 0. Try again.");
System.out.print("What will be the rate of return?");
rate = input.nextDouble();
}
return rate;
}
public static void calculateInterst( double num[], double investTotal, double rateTotal)
{
double total;
rateTotal = rateTotal / 100;
total = investTotal * rateTotal + investTotal;
}
}
You can use a while or for loop. In this example I used a for loop.
There is documentation in the code to walk you through the logic.
public static void calculateInterest(double num, double investTotal, double rateTotal) {
double total; //keep the total outside loop
rateTotal = rateTotal / 100; //your percent to decimal calculation
total = investTotal * rateTotal + investTotal; //intial calculation
for (int i = 1; i < num; i++) {//for loop starting at 1 because we alreay calculated the first
total += (total * rateTotal);//just calculate the rate of change
}
System.out.println(total);//either output it or return it. Whatever you want to do from here.
}
I hope this helps!
You can use below code:
where months is the investment duration in months,
investment is the amount that is being invested,
rate is the interest rate. e.g. 0.045
public static double calculateTotal(int months, double investment, double rate) {
double total = investment;
for (int i=1; i <= months; i++) {
total = total + (total * rate);
}
return total;
}

Program output is NaN instead of float

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.

Error when adding parenthesis in multiplying int and double in java why?

This is a working code but I am wondering after a full research on multiplying ints and doubles in Java I still can't see why the snippet below the code would give an error. Any help please?
public class Arithmetic {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double mealCost = scan.nextDouble(); // original meal price
int tipPercent = scan.nextInt(); // tip percentage
int taxPercent = scan.nextInt(); // tax percentage
scan.close();
// Calculate Tax and Tip:
double tip = mealCost * tipPercent / 100; //HERE IS MY PROBLEM
double tax = mealCost * taxPercent / 100; //HERE IS MY PROBLEM
// cast the result of the rounding operation to an int and save it as totalCost
int totalCost = (int) Math.round(mealCost + tax + tip);
System.out.println("The total meal cost is " + totalCost + " dollars.");
}
}
Knowing that this answer is more logical and gives a different value than the one above?!
double tip = meal * (tipPercent/100);
double tax = meal * (taxPercent/100);
In your 1st example, the multiplication is performed first, resulting in a double number that is then divided by 100, giving the correct double result:
mealCost * tipPercent / 100;
In your 2nd version, an integer division is performed first, resulting in an integer result. Assuming that tipPercent less than 100, the result will be zero.
If you like the second version better, just use a floating point constant:
double tip = meal * (tipPercent/100.0);
Let's imagine:
int tipPercent = 10;
double mealCost = 100.123d;
And
double tip = mealCost * tipPercent / 100;
1. 100.123(double) * 10(int) = 1001.23(double)
2. 1001.23(double) / 100(int) = 10.0123(double)
In the second:
double tip = mealCost * (tipPercent / 100);
10(int) / 100(int) = 0(int)
100.123(double) * 0 = 0(double)

how to get two variables to print with one in decimal form

I am very new. apologies in advance for my coding. I need to print a table that shows year and then a tab over, and then the value with a next line. The value has to be in decimal form.
I have been reading and searching and mixing my code around. I have found it for 1 variable but not for two in same line. I have tried the printf, I have tried the good ol 100 / 100.0 and I either get errors or the decimal never goes to 2 places. I do not need it rounded, just with 2 spaces after. I am obviously going wrong somewhere. I would appreciate any assistance.
import java.util.Scanner;
public class Investment1 {
public static double futureInvestmentValue(double investmentAmount, double monthlyInterestRate, int years){
double principal = 0.0;
double futureInvestmentValue = 0;
for (years = 1; years <=30; years++){
//calculate futureInvestmentValue
futureInvestmentValue = (investmentAmount * (Math.pow (1 + monthlyInterestRate, years * 12)));
System.out.print(years + "\t" + futureInvestmentValue + "\n");
}//end for
return futureInvestmentValue;
}//end futureInvestmentValue
public static void main(String[] args){
Scanner input = new Scanner (System.in);
//obtain Investment amount
System.out.print("Enter Investment amount: ");
double investmentAmount = input.nextDouble();
//obtain monthly interest rate in percentage
System.out.print("Enter annual interest rate in percentage: ");
double annualInterestRate = input.nextDouble();
double monthlyInterestRate = (annualInterestRate / 1200);
int years = 30;
System.out.println("Years\t" + "Future Value");
System.out.print(years + "\t");
System.out.print(years + "\t" + ((int)(futureInvestmentValue(investmentAmount, monthlyInterestRate, years))) + "\n");
}//end main
}//end Investment
You can use system.out.format():
System.out.format("%d \t %.2f", years, futureInvestmentValue);
you should read about format strings, heres a simple usage example:
System.out.println(String.format("%d %.2f",myint,myfloat));
myint will be printed as an integer (even if it's a floating point value) due to the use of the %d in the format string.
myfloat will be printed as a decimal number with 2 digits after the decimal point, thanks to the %f.2 part in the format string.

Categories