建立靜態的公式類別
在這個情境中,我們有一個 Formula 類別,裡面包含多個數學公式的方法,能讓許多使用我們程式碼的開發者受益。你將加入一個用來計算速度的公式,讓大家可以直接使用,如此一來,使用你程式碼的開發者就不需要為相同的速度計算重寫程式,節省寶貴時間。
本練習屬於課程
Java 物件導向程式設計入門
練習說明
- 將
Formula類別設為static類別。 - 建立一個
static的calculateSpeed方法,回傳double,並接收兩個double參數:distance與time。 calculateSpeed方法應回傳以distance除以time的運算結果。- 在
main方法內,直接呼叫Formula類別的calculateSpeed(不建立實例),並以distance設為165.00、time設為15.00來列印其運算結果。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
public class Main {
// Mark Formula as static
____ class Formula{
// Create the calculateSpeed static method
____ ____ calculateSpeed(double ____, double ____) {
return ____ / ____;
}
}
public static void main(String[] args) {
// Print the result of the calculateSpeed method with the correct parameters
System.out.println(Formula.____(____, ____));
}
}