嘗試在控制猜數(shù)游戲的 while 循環(huán)中創(chuàng)建一個隨機(jī)數(shù)生成器。問題是“太高”和“太低”提示會說一個數(shù)字(例如:35)太低,但隨后會說嵌套輸入數(shù)字(例如:36)太高。然后,當(dāng)我在嵌套的 while 循環(huán)中移動調(diào)用隨機(jī)函數(shù)時,它每次都會生成相同的隨機(jī)數(shù)。我嘗試將對隨機(jī)函數(shù)的調(diào)用移動到我最內(nèi)層的循環(huán),但隨后它生成了相同的隨機(jī)數(shù)。當(dāng)前,它在外部 while 循環(huán)中,但隨后出現(xiàn)高/低問題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貢獻(xiàn)1806條經(jīng)驗(yàn) 獲得超5個贊
我想建議您可能會考慮的一些更改:
使用
boolean
forcorrect
而不是int
在: 它是多余的之后立即刪除您的
if
聲明while
do-while
當(dāng)循環(huán)必須至少執(zhí)行一次時使用使用
Integer.compareTo
而不是單獨(dú)比較

qq_花開花謝_0
TA貢獻(xiàn)1835條經(jīng)驗(yàn) 獲得超7個贊
你的內(nèi)部循環(huán)不會終止,這就是為什么你有相同的 randomNumber,更改correct=0值以終止內(nèi)部 while 循環(huán)
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
提交
取消