Miles per gallon

The problem

A car's miles-per-gallon (MPG) can be calculated with the following formula: MPG= Miles driven / Gallons of gas used. Write a program that asks the user to input the number of miles driven and gas used. It should calculate the car's miles-per gallon and display the result on the screen.

Breaking it down

Initialize variables

double miles; // Miles driven
double gallons; // Gallons of fuel
double mpg; // Miles-per-gallon

// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(;

Create method to calculate MPG

 * Method should calculate miles per gallon
 * @param miles
 * @param gallons
 * @return
static double calculateMilesPerGallon(double miles, double gallons) {
    return miles / gallons;

Ask user for input

// Describe to the user what the program will do.
System.out.println("This program will calculate miles per gallon.");

// Get the miles driven.
System.out.print("Enter the miles driven: ");
miles = keyboard.nextDouble();

// Get gallons of fuel
System.out.print("Enter the gallons of fuel used: ");
gallons = keyboard.nextDouble();

Calculate and display results

// call calculateMilesPerGallon to run calculation
mpg = calculateMilesPerGallon(miles, gallons);

// Display the miles-per-gallon.
System.out.print("The miles-per-gallon is " + mpg);


This program will calculate miles per gallon.
Enter the miles driven: 313
Enter the gallons of fuel used: 10
The miles-per-gallon is 31.3

Unit tests

public void calculate_miles_per_gallon () {
    assertTrue(MilesPerGallon.calculateMilesPerGallon(555, 24) == 23.125);

public void calculate_miles_per_gallon_zero_gallons  () {
    assertTrue(MilesPerGallon.calculateMilesPerGallon(10, 0) == Double.POSITIVE_INFINITY);

Level Up

  • Format MPG
  • Validate user input
  • In the case a user enters in 0 gallons, how should you handle it?