(GasMileage) Drivers are concerned with the mileage their automobiles get. One d
ID: 3854428 • Letter: #
Question
(GasMileage) 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.Explanation / Answer
import java.util.*;
class MPG
{
public static void main (String[] args) throws java.lang.Exception
{
int miles,gallon;
double mpg,total_mpg;
total_mpg = 0;
Scanner input = new Scanner(System.in);
do
{
System.out.println(" Enter the miles driven : ");
miles = input.nextInt();
if(miles < 0)//trip ends
break;
System.out.println(" Enter the gallons used : ");
gallon = input.nextInt();
mpg = (double)miles/(double)gallon;
total_mpg = total_mpg + mpg;
}while(miles >0);
System.out.println(" Total miles per gallon : "+total_mpg);
}
}
Output:
Enter the miles driven : 30
Enter the gallons used : 3
Enter the miles driven : 50
Enter the gallons used : 5
Enter the miles driven : 100
Enter the gallons used : 10
Enter the miles driven : -1
Total miles per gallon : 30.0
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.