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.
Diese Übung ist Teil des Kurses
Introduction to Object-Oriented Programming in Java
Anleitung zur Übung
- Create a
calculateMPGmethod that returns aninttype. - The
calculateMPGmethod should take two parameters: anintmilesDrivenand anintgallonsUsed. - The
calculateMPGshould return the division value ofmilesDrivendivided bygallonsUsed. - Use
myCarobject instance to call and print the value of thecalculateMPGmethod, with the parameter values180and20.
Interaktive Übung
Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.
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
____ calculateMPG(int ____, int ____) {
return ____ / ____;
}
}
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(____, ____));
}
}