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
/******************************************************************************
Online Java Compiler.
Code, Compile, Run and Debug java program online.
Write your code in this editor and press "Run" button to execute it.
*******************************************************************************/
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner( System.in );
float miles,gallon,MPG;
float totalMiles = 0, totalGallons = 0, totalMPG;
/*infinite loop to read miles and gallons until -1 is entered*/
/* in each iteration ask for miles and gallon, calculates MPG by dividing miles
by gallon. also maintain totalMiles and totalGallons to calculate totalMPG */
while(true)
{
System.out.print("Enter Miles driven (-1 to quit) :");
miles = scan.nextFloat();
if(miles == -1) /* if -1 is entered, break to come out of infinite loop*/
break;
System.out.print("Enter Gallons used :");
gallon = scan.nextFloat();
MPG = miles/gallon;
totalMiles = totalMiles + miles;
totalGallons = totalGallons + gallon;
totalMPG = totalMiles/totalGallons;
System.out.println("MPG this trip :" + MPG); /* print MPG and totalMPG on console*/
System.out.println("Total MPG :" + totalMPG);
}
}
}
Please upvote if u like answer otherwise comment for clarification.