// Exercise 4.11 Solution: Gas.java // Program calculates average mpg // Java core packages import java.text.DecimalFormat; // Java extension packages import javax.swing.JOptionPane; public class Gas { // main method begins execution of Java application public static void main( String args[] ) { int miles, gallons, totalMiles = 0, totalGallons = 0; float milesPerGallon, totalMilesPerGallon; String inputMiles, inputGallons, result = ""; // read first number from user as a string inputMiles = JOptionPane.showInputDialog( "Enter miles (-1 to quit):" ); // convert miles from type String to type int miles = Integer.parseInt( inputMiles ); // exit if the input is equal to -1 // otherwise, proceed with the program while ( miles != -1 ) { // read second number from user as String inputGallons = JOptionPane.showInputDialog( "Enter gallons:" ); // convert gallons from type String to type int gallons = Integer.parseInt( inputGallons ); totalMiles += miles; totalGallons += gallons; DecimalFormat twoDigits = new DecimalFormat( "0.00" ); if ( gallons != 0 ) { milesPerGallon = (float) miles / gallons; result = "MPG this tankful: " + twoDigits.format( milesPerGallon ) + "\n"; } totalMilesPerGallon = (float) totalMiles / totalGallons; result += "Total MPG: " + twoDigits.format( totalMilesPerGallon ) + "\n"; JOptionPane.showMessageDialog( null, result, "Milage", JOptionPane.INFORMATION_MESSAGE ); // input new value for miles and // convert from String to int inputMiles = JOptionPane.showInputDialog( "Enter miles (-1 to quit):" ); miles = Integer.parseInt( inputMiles ); } // end while loop System.exit( 0 ); } // end method main } // end class Gas