加入具有回傳型別的類別方法
汽車有一項效能指標「每加侖英里數」(miles per gallon,MPG),可以告訴駕駛燃料消耗率。你將建立一個名為 calculateMPG 的方法來計算 MPG。calculateMPG 方法會使用行駛的英里數與使用的加侖數進行計算,並回傳正確的每加侖英里數。
本練習屬於課程
Java 物件導向程式設計入門
練習說明
- 建立一個
calculateMPG方法,回傳型別為int。 calculateMPG方法需接受兩個參數:intmilesDriven與intgallonsUsed。calculateMPG應回傳milesDriven除以gallonsUsed的商。- 使用
myCar物件實例來呼叫並印出calculateMPG的回傳值,參數值為180與20。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
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(____, ____));
}
}