← 從零開始學 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 的所有質數。