尝试在控制猜数游戏的 while 循环中创建一个随机数生成器。问题是“太高”和“太低”提示会说一个数字(例如:35)太低,但随后会说嵌套输入数字(例如:36)太高。然后,当我在嵌套的 while 循环中移动调用随机函数时,它每次都会生成相同的随机数。我尝试将对随机函数的调用移动到我最内层的循环,但随后它生成了相同的随机数。当前,它在外部 while 循环中,但随后出现高/低问题import java.util.Scanner;import java.util.Random;public class numberGuessingGame{ public static void main (String[] args) { int randomNumber, userNumber = 0, guesses = 0, correct; final int MAX = 100; char playAgain, playGame = 'y'; //ask user if they wish to play System.out.println("Would you like to play the Number Guessing Game? y / n"); Scanner scan = new Scanner (System.in); playGame = scan.next().charAt(0); Random generator = new Random(); //while loop to continue to exacute game as long as user enters 'y' while (playGame == 'y'){ if (playGame != 'y') break; randomNumber = generator.nextInt(MAX) + 1; //flag correct = 0; //loop to control the round while (correct == 0) { //get user number System.out.println("Please pick a number between 1 and 100."); userNumber = scan.nextInt(); //high and low sugguestion if (userNumber > randomNumber) System.out.println("Number is too high, try something lower."); if (userNumber < randomNumber) System.out.println("Number is too low, try something higher."); if (userNumber == randomNumber){ System.out.println("That number is correct!"); System.out.println("Would you like to play again? y/n"); playGame = scan.next().charAt(0); } guesses++; System.out.println("You have guessed " + guesses + " times!"); } }
2 回答
忽然笑
TA贡献1806条经验 获得超5个赞
我想建议您可能会考虑的一些更改:
使用
boolean
forcorrect
而不是int
在: 它是多余的之后立即删除您的
if
声明while
do-while
当循环必须至少执行一次时使用使用
Integer.compareTo
而不是单独比较
qq_花开花谢_0
TA贡献1835条经验 获得超7个赞
你的内部循环不会终止,这就是为什么你有相同的 randomNumber,更改correct=0值以终止内部 while 循环
if (userNumber == randomNumber){
System.out.println("That number is correct!");
System.out.println("Would you like to play again? y/n");
playGame = scan.next().charAt(0);
correct=1; //Just to remove correct=0 value
}
添加回答
举报
0/150
提交
取消