Saturday, August 27, 2016

// // Leave a Comment

Java Gas Mileage Calculator

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.
/**
 *
 * @Author: Aghatise Osazuwa
 * Website: www.cscprogrammingtutorials.com
 *
 * Exercise 4.17 - Gas Mileage
 *
 */ 

import java.util.Scanner;

public class GasMileage {

    public static void main(String[] args) {

        int miles;  
        int gallons;
        int totalMiles = 0;
        int totalGallons = 0;

        Scanner input = new Scanner(System.in); 

        System.out.println("This Application Determines Calculates And Displays"
                + " The Miles Per Gallon Obtained For Each Trip And Print The" 
                + " Combined Miles Per Gallon Obtained For All Trips.\n");

        System.out.println("\nEnter miles driven or -1 to Quit: ");
        miles = input.nextInt();
        
        while (miles != -1 ) {            
            System.out.println("Enter gallons used: ");
            gallons = input.nextInt();
            System.out.println("\nMiles driven for this trip: " + miles);
            System.out.println("Gallons used for this trip: " + gallons);
            totalMiles += miles;
            totalGallons += gallons;
            System.out.printf("\nMiles per gallon for this trip: %f\nCombined Miles "
                    + "per gallon: %f\n",(double)miles/gallons, (double)totalMiles/totalGallons);
            
            System.out.println("\nEnter miles driven or -1 to Quit: ");
            miles = input.nextInt();
        }
        System.out.println();
    }  
}

Java Gas Mileage Calculator
Program Output


Click here to see other answers to Dietel's Java How to Program exercises.

0 comments:

Post a Comment


DISCLAIMER: Opinions expressed in comments are those of the comment writers alone and does not reflect or represent the views of the post author. We reserve the right to delete any post deemed inappropriate or offensive and/or spammy. Please do not use abusive words/hate speech.

I Appreciate your valuable Feedback. So, Please DO NOT SPAM - Spam comments will be deleted immediately.

Don't use brand name in name field and you're not allowed to use links in comments unless it's necessary. Such comments will be removed immediately.

Thanks.