我有一個需要從 0 到 100 設置的代碼,并且有可能將零作為正確答案。我已將我的最終整數設置為 MAX(100)/MIN(0)。但 0 永遠不是正確答案。我有 4 年的編程經驗和 2 年的 Java 經驗,但似乎任何問題 1-100 或 1-任何其他 MAX 都可以。請幫助,或解釋 0 是否不是允許的選擇。import java.util.Random;import java.util.Scanner;public class GuessingGame { public static void main(String[] args) { Scanner scan = new Scanner(System.in); Random generator = new Random(); int MIN = 0; int MAX = 100; int answer; int guess; String another = "y"; boolean flag = false; boolean anotherFlag = true; while(anotherFlag){ answer = generator.nextInt(MAX) + 1; System.out.println("I'm thinkin of a number between 0 and " + MAX ); System.out.println("Can you guess what it is? \n"); flag = false; while(!flag) { guess = scan.nextInt(); if(guess == answer){ System.out.println("You guessed correctly"); flag = true; } else{ System.out.println("That was wrong, try again."); } } System.out.println("Want to Play again?(y/n)"); another = scan.next(); if(another.equalsIgnoreCase("y") == true){ anotherFlag = true; } else{ anotherFlag = false; } }感謝您的幫助。
1 回答

飲歌長嘯
TA貢獻1951條經驗 獲得超3個贊
似乎問題出在
answer = generator.nextInt(MAX) + 1;
你的答案范圍是 1 - MAX。
如果你想生成一個介于 0 - MAX 之間的隨機數,其中 MAX = 100。你應該寫 -
answer = generator.nextInt(MAX+1);
因為根據 Java API (java v8),
public int nextInt(int bound)
返回介于 0(包括)和指定值(不包括)之間的偽隨機、均勻分布的 int 值
添加回答
舉報
0/150
提交
取消