Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

(Gas Mileage) Drivers are concerned with the mileage their automobiles get. One

ID: 3846115 • Letter: #

Question

(Gas Mileage) Drivers are concerned with the mileage their automobiles get. One driver has kept track of serveral 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 calcuate 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 reults. Use class Scanner and sentinel-controlled reptition to obtain the data from the user.

Explanation / Answer

import java.util.Scanner;

public class GasMileage {

   public static void main(String args[]) {

       Scanner input = new Scanner(System.in);

       int currentMiles=0,totalMiles=0;

       int currentGallons=0,totalGallons=0;

       int sentinel = -1;

       while(true){

           System.out.println("Enter the miles driven in your trip or enter -1 to stop");

           currentMiles = input.nextInt();

           if(currentMiles == sentinel) {

               System.out.println("Thanks for your inputs...");

               break;

           }else {

               System.out.println("Enter gallons used in this trip");

               currentGallons = input.nextInt();

               totalGallons+=currentGallons;

               totalMiles+=currentMiles;

               float currentAverage = (float)currentMiles / currentGallons;

               System.out.println("Average for the trip:" + currentAverage);

           }      

       }

       input.close();

       if(totalMiles < 0) {

           System.out.println("You have not entered information of your trips");

       } else {

       System.out.println("Total average for all trips is:"+(float)totalMiles / totalGallons);

}

   }

}