Get startedGet started for free

Adding class methods with return types

Cars have a performance metric called miles per gallon that tells the driver the fuel consumption rate. You will create a method to calculate the miles per gallon called calculateMPG. The calculateMPG method uses the number of miles driven and the amount of gallons used to calculate and return the correct miles per gallon unit.

This exercise is part of the course

Introduction to Object-Oriented Programming in Java

View Course

Exercise instructions

  • Create a calculateMPG method that returns an int type.
  • The calculateMPG method should take two parameters an int milesDriven and an int gallonsUsed.
  • The calculateMPG should return the division value of milesDriven divided by gallonsUsed.
  • Use myCar object instance to call and print the value of the calculateMPG method, with the parameter values 180 and 20.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

class Main {  

    static class Car {
        String color;
        String model;
        int year;

        Car(String color, String model, int year) {
            this.color = color;
            this.model = model;
            this.year = year;
        }

        void turnEngineOn() {
            System.out.println("engine is on");            
        }

        // Create the calculateMPG method 
        ____ ____(____ ____, ____ ____) {
            ____ ____ / ____;
        }
    }
    
    public static void main(String[] args) {
        Car myCar = new Car("red", "camry", 2022);
        // Print out value for when calculateMPG is used 
        System.out.println(myCar.calculateMPG(____, ____));
    }
    
}
Edit and Run Code