(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 repetition to obtain the data from the user .
Gas Mileage Calculate Miles in Java
GasMileage.java
/*
* Filename: GasMileage.java
*
* Description: Exercise 4.17 - Gas Mileage
*
* @Author: Bilal Tahir Khan Meo
* Website: https://codeblah.com
*
* =====================================================================================
*/
public class GasMileage{
double totalMiles, totalGallons;
public double getTripMPG(int miles, int gallons){
totalMiles += miles;
totalGallons += gallons;
return miles / (double)gallons;
}
public double getTotalMiles(){
return totalMiles;
}
public double getTotalGallons(){
return totalGallons;
}
public double getTotalMPG(){
return totalMiles / totalGallons;
}
}
GasMileageTest.java
/*
* Filename: GasMileageTest.java
*
* Description: Exercise 4.17 - Gas Mileage
*
* @Author: Bilal Tahir Khan Meo
* Website: https://codeblah.com
*
* =====================================================================================
*/
import java.util.Scanner;
public class GasMileageTest{
public static void main(String[] args){
int miles, gallons;
char cont = 'y';
Scanner sc = new Scanner(System.in);
GasMileage mileage = new GasMileage();
while(cont != 'n'){
System.out.println("\n*********************\n");
System.out.print("Enter Gas Mileage for this trip: ");
miles = sc.nextInt();
System.out.print("Enter Gallons used for this trip: ");
gallons = sc.nextInt();
System.out.printf("Your MPG for this trip is: %.2f\n",
mileage.getTripMPG(miles, gallons));
System.out.print("Add another trip? (y/n): ");
cont = sc.next().charAt(0);
}
System.out.println("\n*********************\n");
System.out.println("COMBINED TOTAL MPG");
System.out.printf("Combined mileage: %.2f\nCombined gallon useage: %.2f\n",
mileage.getTotalMiles(), mileage.getTotalGallons());
System.out.printf("Your combined MPG for all trips is: %.2f\n", mileage.getTotalMPG());
}
}