44.2k views
1 vote
(Gas Mileage) 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 iteration to obtain the data from the user.

User Scheintod
by
4.6k points

1 Answer

1 vote

Answer:

import java.util.*;

public class Main {

public static void main(String[] args) {

double milesPerGallon = 0;

int totalMiles = 0;

int totalGallons = 0;

double totalMPG = 0;

Scanner input = new Scanner(System.in);

while(true){

System.out.print("Enter the miles driven: ");

int miles = input.nextInt();

if(miles <= 0)

break;

else{

System.out.print("Enter the gallons used: ");

int gallons = input.nextInt();

totalMiles += miles;

totalGallons += gallons;

milesPerGallon = (double) miles/gallons;

totalMPG = (double) totalMiles / totalGallons;

System.out.printf("Miles per gallon for this trip is: %.1f\\", milesPerGallon);

System.out.printf("Total miles per gallon is: %.1f\\", totalMPG);

}

}

}

}

Step-by-step explanation:

Initialize the variables

Create a while loop that iterates until the specified condition is met inside the loop

Inside the loop, ask the user to enter the miles. If the miles is less than or equal to 0, stop the loop. Otherwise, for each trip do the following: Ask the user to enter the gallons. Add the miles and gallons to totalMiles and totalGallons respectively. Calculate the milesPerGallon (divide miles by gallons). Calculate the totalMPG (divide totalMiles by totalGallons). Print the miles per gallon and total miles per gallon.

User Soteria
by
4.5k points