首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Java 猜數字遊戲完整實現

     編輯:程式設計疑難解答

需求

控制台程序:隨機生成 1-100 數字,用戶輸入猜測,提示大/小,猜中顯示次數,詢問是否繼續。

完整代碼

import java.util.InputMismatchException;
import java.util.Scanner;

public class GuessNumber {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        boolean playAgain = true;
        while (playAgain) {
            int target = (int)(Math.random() * 100) + 1;
            int count = 0;
            int min = 1, max = 100;
            System.out.println("=== 猜數字遊戲開始 ===");
            while (true) {
                System.out.printf("請輸入 (%d-%d): ", min, max);
                try {
                    int guess = sc.nextInt();
                    count++;
                    if (guess > target) {
                        max = guess - 1;
                        System.out.println("太大了!");
                    } else if (guess < target) {
                        min = guess + 1;
                        System.out.println("太小了!");
                    } else {
                        System.out.printf("恭喜!共猜了 %d 次%n", count);
                        break;
                    }
                } catch (InputMismatchException e) {
                    System.out.println("請輸入整數!");
                    sc.next(); // 清除無效輸入
                }
            }
            System.out.print("再玩一次?(y/n): ");
            String ans = sc.next();
            playAgain = ans.equalsIgnoreCase("y");
            if (playAgain) System.out.println();
        }
        System.out.println("謝謝遊玩!");
    }
}

關鍵點

  • 使用 Math.random() 生成 1-100 隨機數。
  • 維護 min/max 縮小提示範圍,體驗更好。
  • 捕獲 InputMismatchException 處理非數字輸入,並清空緩衝區。
  • 外層循環控制多輪遊戲。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved