在下面的代码中第一个方法(generateRandomNumber)生成1到10之间的随机数。然后第二个方法(guessRandomNumber)允许用户猜测数字。我遇到的问题是,当用户猜错号码时,它会生成另一个随机数而不是初始数。因此,即使输入每个可能的数字,用户也可以猜测并且永远不会正确。任何人都可以建议我如何改变这一点。
第一种方法(生成数字):
public static int generateRandomNumber() {
Random random = new Random();
// Declaring int for random number and defaulting to 0
int randomNumber = 0;
// Assigning randomNumber between 1 and 10
randomNumber = random.nextInt(10);
randomNumber++;
return randomNumber;
}// end of generateRandomNumber
第二种方法(猜数字):
public static void guessRandomNumber() {
// declare var for user guess and default to zero
int userGuess = 0;
boolean validNumber=false;
boolean correctGuess=false;
do{
do{
try{
validNumber=true;
// Get user guess (between 1 and 10)
System.out.println("Please enter a number between 1 and 10...");
userGuess = scanner.nextInt();
}catch (Exception ex){
System.out.println("Sorry invalid entry...");
//Flush scanner
scanner.next();
validNumber=false;
}
}while (!validNumber);
if (userGuess == generateRandomNumber()) {
System.out.println("Guess correct, well done!");
correctGuess=true;
} else {
System.out.println("Sorry guess Incorrect please try again!");
correctGuess=false;
}
}while (!correctGuess);
}// end ofGuessRandomNumber
尝试:
public static void guessRandomNumber() {
// declare var for user guess and default to zero
int userGuess = 0;
boolean validNumber=false;
boolean correctGuess=false;
int secretNumber=generateRandomNumber();
do{
do{
try{
validNumber=true;
// Get user guess (between 1 and 10)
System.out.println("Please enter a number between 1 and 10...");
userGuess = scanner.nextInt();
}catch (Exception ex){
System.out.println("Sorry invalid entry...");
//Flush scanner
scanner.next();
validNumber=false;
}
}while (!validNumber);
if (userGuess == secretNumber) {
System.out.println("Guess correct, well done!");
correctGuess=true;
} else {
System.out.println("Sorry guess Incorrect please try again!");
correctGuess=false;
}
}while (!correctGuess);
}// end ofGuessRandomNumber
答案 0 :(得分:2)
您需要先在用户猜测之前生成随机数,然后将其存储在变量中。然后,而不是在行
中调用generateRandomNumber()
if (userGuess == generateRandomNumber())
您需要将其与该变量进行比较。
答案 1 :(得分:1)
您应该在第一次执行循环之前生成随机数。将其保存在名为correctNumber
的变量中,然后测试userGuess == correctNumber
。