尝试在控制猜数游戏的 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!");
}
}
忽然笑
qq_花开花谢_0
相关分类