添加带返回类型的类方法
汽车有一个名为每加仑行驶英里数(miles per gallon,MPG)的性能指标,用于衡量燃油消耗。您将创建一个名为 calculateMPG 的方法来计算 MPG。calculateMPG 方法使用行驶英里数和使用的加仑数来计算并返回正确的 MPG。
本练习是课程的一部分
Java 面向对象编程入门
练习说明
- 创建一个返回类型为
int的calculateMPG方法。 calculateMPG方法应接收两个参数:intmilesDriven和intgallonsUsed。calculateMPG应返回milesDriven除以gallonsUsed的商。- 使用
myCar对象实例,传入参数值180和20,调用并打印calculateMPG方法的返回值。
交互式实操练习
通过完成这段示例代码来试试这个练习。
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(____, ____));
}
}