Question: 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.
1 2 |
/**<br /> *<br /> * @Author: Aghatise Osazuwa<br /> * Website: www.cscprogrammingtutorials.com<br /> *<br /> * Exercise 4.17 - Gas Mileage<br /> *<br /> */ <br /><br />import java.util.Scanner;<br /><br />public class GasMileage {<br /><br /> public static void main(String[] args) {<br /><br /> int miles; <br /> int gallons;<br /> int totalMiles = 0;<br /> int totalGallons = 0;<br /><br /> Scanner input = new Scanner(System.in); <br /><br /> System.out.println("This Application Determines Calculates And Displays"<br /> + " The Miles Per Gallon Obtained For Each Trip And Print The" <br /> + " Combined Miles Per Gallon Obtained For All Trips.n");<br /><br /> System.out.println("nEnter miles driven or -1 to Quit: ");<br /> miles = input.nextInt();<br /> <br /> while (miles != -1 ) { <br /> System.out.println("Enter gallons used: ");<br /> gallons = input.nextInt();<br /> System.out.println("nMiles driven for this trip: " + miles);<br /> System.out.println("Gallons used for this trip: " + gallons);<br /> totalMiles += miles;<br /> totalGallons += gallons;<br /> System.out.printf("nMiles per gallon for this trip: %fnCombined Miles "<br /> + "per gallon: %fn",(double)miles/gallons, (double)totalMiles/totalGallons);<br /> <br /> System.out.println("nEnter miles driven or -1 to Quit: ");<br /> miles = input.nextInt();<br /> }<br /> System.out.println();<br /> } <br />}<br /> |
Program Output |
Click here to see other answers to Dietel’s Java How to Program exercises.