In: Computer Science
Drivers are concerned with the mileage
obtained by their automobiles. One driver has kept track of
several trips by recording miles driven and gallons used for
each trip. Develop a java program that uses a while statement
to input the miles driven and gallons used 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 tankfuls up to this point.
Enter miles driven (-1 to quit): 287
Enter gallons used: 13
MPG this trip: 22.076923
Total MPG: 22.076923
Enter miles driven (-1 to quit): 200
Enter gallons used: 10
MPG this trip: 20.000000
Total MPG: 21.173913
Enter the miles driven (-1 to quit): 120
Enter gallons used: 5
MPG this trip: 24.000000
Total MPG: 21.678571
Enter the miles used (-1 to quit): -1
(If you still have any doubts regarding this answer please comment I will definitely help)
Key points to remember:
Code Explanation:
Code:
import java.lang.*;
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args)
{
double MPG, Total_MPG;
int gallons, miles, Total_miles = 0, Total_gallons =
0;
Scanner sc = new Scanner(System.in);
while(true)
{
System.out.print("Enter miles
driven (-1 to quit): ");
miles = sc.nextInt();
if(miles == -1)
break;
Total_miles = Total_miles +
miles;
System.out.print("Enter gallons
used: ");
gallons = sc.nextInt();
Total_gallons = Total_gallons +
gallons;
MPG = (double) miles/gallons;
System.out.printf("MPG this trip:
"+String.format("%.6f", MPG));
Total_MPG = (double)
Total_miles/Total_gallons;
System.out.printf("\nTotal MPG:
"+String.format("%.6f", Total_MPG)+"\n");
}
}
}
Sample O/P1:
Enter miles driven (-1 to quit): 287
Enter gallons used: 13
MPG this trip: 22.076923
Total MPG: 22.076923
Enter miles driven (-1 to quit): 200
Enter gallons used: 10
MPG this trip: 20.000000
Total MPG: 21.173913
Enter miles driven (-1 to quit): 120
Enter gallons used: 5
MPG this trip: 24.000000
Total MPG: 21.678571
Enter miles driven (-1 to quit): -1
Sample O/P2:
Enter miles driven (-1 to quit): 155
Enter gallons used: 20
MPG this trip: 7.750000
Total MPG: 7.750000
Enter miles driven (-1 to quit): 257
Enter gallons used: 30
MPG this trip: 8.566667
Total MPG: 8.240000
Enter miles driven (-1 to quit): -1
Code Screenshot:
Sample O/P1 screenshot:
Sample O/P2 screenshot: