首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 實作猜數字小遊戲:完整代碼與邏輯解析

     編輯:Java 相關知識

編寫一個「猜數字」遊戲是 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(); // 清除緩衝區無效輸入
            }
        }
    }
}

關鍵技術點解析

1. 隨機數生成

Math.random() 回傳 [0.0, 1.0) 的 double,乘以 100 並轉 int 可得 [0, 99],再 +1 即為 [1, 100]。

2. 異常處理與輸入驗證

使用 try-catch 捕捉 InputMismatchException(由 scanner.nextInt() 拋出),搭配 scanner.next() 清除緩衝區殘留的非數字字元,避免無限迴圈。這比原始碼中的遞迴呼叫 guess(i) 更安全,避免棧溢位風險。

3. 時間統計

採用 System.currentTimeMillis() 記錄開始與結束時間差,換算為秒;SimpleDateFormat 格式化結束時間輸出。

4. 程式結構優化

  • 將輸入邏輯封裝為獨立方法 getValidIntInput,符合單一職責原則。
  • 移除原始碼中 class calssOne 的拼寫錯誤與靜態方法濫用,改為實例方法與區域變數。
  • 關閉 Scanner 釋放資源。

延伸練習建議

  • 新增難度選項:簡單(1-50)、普通(1-100)、困難(1-1000)。
  • 記錄最高分(最少次數/最短時間)至檔案。
  • 改寫為 Swing/JavaFX 圖形介面版本。

這個小遊戲雖然簡單,卻涵蓋了隨機數、迴圈、條件判斷、異常處理、時間 API 等 Java 核心基礎,是入門後鞏固語法的最佳實戰題目。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved