← 從零開始學 Java 第 23 課,共 88 課 · 10 XP

方法

理論與題目說明

機器翻譯,尚未經母語人士審閱。

方法是類別裡有名字的程式碼區塊:

public class Main {
    static void greet() {                 // void——不回傳任何東西
        System.out.println("Hello!");
    }

    static int square(int x) {            // 回傳 int
        return x * x;
    }

    public static void main(String[] args) {
        greet();
        System.out.println(square(7));    // 49
    }
}
  • static——方法屬於類別,不用物件就能呼叫(從 static main 只能直接呼叫 static 方法——不然會出現錯誤 non-static method cannot be referenced from a static context);
  • 回傳型別寫在名字前面。return 結束方法;
  • 方法可以用任何順序宣告——在 main 上面或下面都可以。

題目。 寫一個 static boolean isPrime(int n),用空白分隔輸出從 2 到 n 的所有質數。

免費註冊,就能直接在瀏覽器裡解這道題:程式碼編輯器、執行、測試檢查和提示。