Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
Java Programming Question?
Here's my code. But why the hell doesn't this work? No compiler errors, so it must be an error on my part. Whenever I run it for some reason it omits the last value for the average. I ran it with the values: X= 100 miles traveled, 100 miles traveled, 100 miles traveled and Y= 5 gallons, 4 gallons, 10 gallons. When it calculates the average its not 18.33 like its supposed to be, its 15 like it omitted including the last value for each coord yet still divided it by 3? Help please?
import java.util.Scanner;
public class Mpgcalc {
/**
* @param args the command line arguments
*/
public static void main( String[] args )
{
// TODO code application logic here
Scanner input = new Scanner( System.in );
int miles;
int gallons;
int counter;
double total;
double average;
double mpg;
total = 0;
counter = 0;
System.out.print( "Enter miles traveled: ");
miles = input.nextInt();
System.out.print( "Enter amount of gallons used: ");
gallons = input.nextInt();
mpg = ( miles/gallons );
System.out.printf( "\nYour gas mileage for your trip was %.2f\n", mpg );
System.out.printf( "Enter miles traveled (or type -1 to stop adding \n additional values): ");
miles = input.nextInt();
while ( miles != -1 )
{
System.out.print( "Enter amount of gallons used: ");
gallons = input.nextInt();
mpg = ( miles / gallons );
System.out.printf( "\nYour gas mileage for your trip was %.2f\n", mpg );
System.out.printf( "Enter miles traveled (or type -1 to stop adding \n additional values): ");
miles = input.nextInt();
}
if ( counter != 0 )
{
average = ( total/counter );
System.out.printf( "\nTotal number of trips entered is %d\n", counter );
System.out.printf( "Average miles per gallon is %.2f\n", average );
}
else
System.out.println( "No input received from user. Program Terminating" );
}
}
3 Answers
- ?Lv 610 years agoFavorite Answer
Where are you incrementing counter and total
also your formula for mpg is wrong it should be
mpg = (double )miles/gallons;
your way will truncate decimal part
- ?Lv 44 years ago
Why roll your guy or woman whilst there is in all probability a calendar widget you are able to reuse? via the way, the Java API itself supplies many functional training and interfaces: Date, Calendar, GregorianCalendar, DateFormat, and SimpleDateFormat.
- djbckrLv 510 years ago
In Java, if you divide integers, it will return an integer. Either cast miles and gallons to a double, or make them double in your variable declaration.