控制台程序:隨機生成 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 處理非數字輸入,並清空緩衝區。