JAVA-重复10次后结束循环



我正在编写一个游戏,用户需要猜测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--;
}

最新更新