編寫一個「猜數字」遊戲是 Java 初學者練習流程控制、隨機數生成與使用者輸入處理的經典練習。本文提供一個功能完整的主控台版本實作,並詳細解析核心邏輯,幫助你快速掌握 Java 基礎語法的實戰應用。
遊戲規則簡單:系統隨機生成一個 1 到 100 之間的整數,玩家反覆輸入猜測,系統提示「大了」、「小了」或「正確」,並統計猜測次數與耗時。程式還需處理非數字輸入的異常情況,確保健壯性。
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class GuessNumberGame {
public static void main(String[] args) {
// 1. 生成 1-100 的隨機答案
int answer = (int) (Math.random() * 100) + 1;
long startTime = System.currentTimeMillis();
Scanner scanner = new Scanner(System.in);
System.out.println("*********** 猜數字小遊戲,你 Hold 得住嗎?*********");
System.out.println("提示:答案是一個 1 到 100 之間的整數。");
// 2. 主迴圈:最多猜 99 次(實際上不會用完)
for (int attempt = 1; attempt < 100; attempt++) {
System.out.print("請輸入你第 " + attempt + " 次的猜測:");
int guess = getValidIntInput(scanner, attempt);
// 3. 判斷邏輯
if (guess > answer) {
System.out.println("不好意思,您猜的數字大於答案!");
} else if (guess < answer) {
System.out.println("不好意思,您猜的數字小於答案!");
} else {
// 猜中處理
long endTime = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("\n*********** 正確答案:" + answer + " ***************");
if (attempt == 1) {
System.out.println("Perfect!! 恭喜您,一次就中!!");
} else if (attempt < 10) {
System.out.println("Good job! 您總共猜了 " + attempt + " 次,還要持續加油!!");
} else {
System.out.println("Not bad! 您總共猜了 " + attempt + " 次,任重而道遠啊!");
}
System.out.println("結束時間:" + sdf.format(new Date()));
System.out.println("所用時間:" + (endTime - startTime) / 1000 + " 秒");
scanner.close();
return; // 結束遊戲
}
}
scanner.close();
}
/**
* 取得合法的整數輸入,若輸入非數字則提示重新輸入
*/
private static int getValidIntInput(Scanner scanner, int attempt) {
while (true) {
try {
return scanner.nextInt();
} catch (Exception e) {
System.out.println("您輸入的不是數字,請重新輸入第 " + attempt + " 個數字:");
scanner.next(); // 清除緩衝區無效輸入
}
}
}
}
Math.random() 回傳 [0.0, 1.0) 的 double,乘以 100 並轉 int 可得 [0, 99],再 +1 即為 [1, 100]。
使用 try-catch 捕捉 InputMismatchException(由 scanner.nextInt() 拋出),搭配 scanner.next() 清除緩衝區殘留的非數字字元,避免無限迴圈。這比原始碼中的遞迴呼叫 guess(i) 更安全,避免棧溢位風險。
採用 System.currentTimeMillis() 記錄開始與結束時間差,換算為秒;SimpleDateFormat 格式化結束時間輸出。
getValidIntInput,符合單一職責原則。class calssOne 的拼寫錯誤與靜態方法濫用,改為實例方法與區域變數。Scanner 釋放資源。這個小遊戲雖然簡單,卻涵蓋了隨機數、迴圈、條件判斷、異常處理、時間 API 等 Java 核心基礎,是入門後鞏固語法的最佳實戰題目。