[英]JAVA - End a loop after 10 repeats
我正在編寫一個游戲,用戶需要猜測 0-100 之間的數字。 用戶有 10 次嘗試猜測正確的數字,每次輸入后,他都需要回復評論。 所以我寫了代碼,一切都很好,但是我在 10 次錯誤猜測后打破循環並在游戲結束后重新開始游戲時遇到了問題。 任何事情都會有所幫助。 提前謝謝你!
Scanner guess = new Scanner (System.in);
Random hundred = new Random ();
System.out.println ("Welcome to Magic Number!");
System.out.println ("I'm thinking about a number between 0-100. You have 10 rounds to guess the right number.");
System.out.println ("Good Luck!");
int number = hundred.nextInt(101);
while (true) {
System.out.println ("What is the number i'm thinking about?");
int guess1 = guess.nextInt();
if (guess1 > number) {
System.out.println ("The number you gueesed is higher than the number i'm thinking about!");
} else if (guess1 < number) {
System.out.println ("This number you guessed is lower than the number i'm thinking about!");
} else if (guess1 == number) {
System.out.println ("Congratulations! You've read my mind!");
break;
}
}
您必須在 while 循環中添加 numberOfTimes 看看下面的代碼:
int numberOfTimes = 10;
while (numberOfTimes > 0) {
System.out.println ("What is the number i'm thinking about?");
int guess1 = guess.nextInt();
if (guess1 > number) {
System.out.println ("The number you gueesed is higher than the number i'm thinking about!");
} else if (guess1 < number) {
System.out.println ("This number you guessed is lower than the number i'm thinking about!");
} else if (guess1 == number) {
System.out.println ("Congratulations! You've read my mind!");
break;
}
numberOfTimes--;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.