本文整理一系列 Java 進階練習題,涵蓋靜態方法調用、隨機數生成、方法重載、階乘溢位處理、組合數計算、漢諾塔遞歸與回文判斷,並提供完整原始碼與執行結果圖示。
題目要求:定義靜態類方法 square,但在 main 中不使用 static 關鍵字調用。解決方案:在 main 中實例化類別,透過物件呼叫實例方法。
// 類的對象實例化
public class SquareIntTest {
public static void main(String[] args) {
for (int x = 1; x <= 10; x++) {
SquareIntTest obj = new SquareIntTest(); // 建立實例
int result = obj.square(x); // 呼叫實例方法
System.out.println("The square of " + x + " is " + result);
}
}
// 自定義求平方數的實例方法(非 static)
public int square(int y) {
return y * y;
}
}


使用 java.util.Random 並指定種子 (seed),展示 nextBoolean()、nextInt()、nextDouble()、nextGaussian() 等方法。
import java.util.Random;
public class Random1000 {
public static void main(String[] args) {
Random r1 = new Random(1000); // 種子為 1000
System.out.println("第一個種子為1000的Random對象");
System.out.println("r1.nextBoolean():\t" + r1.nextBoolean());
System.out.println("r1.nextInt():\t\t" + r1.nextInt());
System.out.println("r1.nextDouble():\t" + r1.nextDouble());
System.out.println("r1.nextGaussian():\t" + r1.nextGaussian());
}
}

觀察以下程式碼,發現 square 方法有兩個版本:參數型別分別為 int 與 double。編譯器根據引數型別自動選擇對應方法,這就是方法重載。
public static int square(int x) { return x * x; }
public static double square(double y) { return y * y; }
重載滿足條件: (1) 方法名相同;(2) 參數型別、個數或順序不同。返回值型別不是判斷依據。


查看 JDK 原始碼可見 println 針對各種基本型別、String、Object 等都有對應的重載版本,故可直接列印多種型別資料。

計算 50! 時 long 型別溢位導致負數。原因:電腦用固定位數儲存數值,超出範圍會截斷二進制表示。解決:使用 java.math.BigInteger 進行大整數運算。

使用 BigInteger 遞歸實現階乘,再計算組合數。
import java.math.BigInteger;
import java.util.Scanner;
public class Zhuheshu {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("請輸入N:"); int n = scanner.nextInt();
System.out.print("請輸入M:"); int k = scanner.nextInt();
System.out.println(ca(n).divide(ca(k).multiply(ca(n - k))));
}
public static BigInteger ca(int m) {
if (m == 1 || m == 0) return BigInteger.valueOf(1);
return BigInteger.valueOf(m).multiply(ca(m - 1));
}
}


經典遞歸算法:將 n-1 個盤子從源柱移至備用柱,再移動最大盤子到目標柱,最後將 n-1 個盤子從備用柱移至目標柱。
import java.util.Scanner;
public class Hannuota {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("請輸入盤子的個數:");
int disks = scanner.nextInt();
final int source = 1, desk = 3, spare = 2;
move(disks, source, desk, spare);
}
public static void move(int disks, int source, int desk, int spare) {
if (disks == 1) System.out.println(source + "->" + desk);
else {
move(disks - 1, source, spare, desk);
System.out.println(source + "->" + desk);
move(disks - 1, spare, desk, source);
}
}
}


利用 StringBuffer.reverse() 反轉字串,逐字元比較原字串與反轉字串。
import java.util.Scanner;
public class Huiwen {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("請輸入一個字符串:");
String str = in.nextLine();
StringBuffer sb = new StringBuffer(str);
sb.reverse();
int n = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == sb.charAt(i)) n++;
}
if (n == str.length()) System.out.println(str + "是回文!");
else System.out.println(str + "不是回文!");
}
}
