作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试编写一个猜数游戏程序,因此程序会生成一个随机数,并且程序会提示太高、太低,直到用户得到它的写入。然而,随机生成器要么每次生成相同的随机数,要么对于一个用户输入说“太高”,然后对紧接着/之后的用户输入说“太低”
我已将随机生成器移至 while 循环内,在这种情况下,它表示输入“太高”,而后面的数字“太低”。当我将随机生成器移到循环之外时,它只会为游戏的每次刺激生成相同的数字。
import java.util.Scanner;
import java.util.Random;
public class NumberGuessingGame {
public static void main(String[] args) {
int randomNumber, userNumber = 0, guesses = 0;
final int MAX = 100;
char playGame = 'y';
Random generator = new Random();
// ask user if they wish to play
System.out.println("Would you like to play the Number Guessing y / n");
Scanner scan = new Scanner(System.in);
playGame = scan.next().charAt(0);
// while loop to continue to execute game as long as the user enters 'y'
while (playGame == 'y') {
if (playGame != 'y')
break;
randomNumber = generator.nextInt(MAX) + 1;
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);
}
// counter to keep running total of times guessed
guesses++;
System.out.println("You have guessed " + guesses + " times!");
}
// break statement skips here when 'n' is entered in
// the game prompting question
System.out.println("Thanks for playing, have a nice day!");
}
}
程序应该为游戏的每次迭代生成一个新的随机数,每次正确猜测随机数后都会提示该随机数。
最佳答案
希望这有助于您澄清问题!
目前,您的随机数生成与游戏的其余部分位于同一循环中,这就是每次您收到新提示时它都会生成新数字的原因。解决此问题的一种方法是创建两个循环。一个循环控制游戏是否继续,并在另一个循环内管理该回合。
//The loop controlling the game
while (playGame == 'y') {
if (playGame != 'y')
break;
randomNumber = generator.nextInt(MAX) + 1;
//Creating a flag to control the inner loop
int correct = 0;
//The loop to control the round.
while (correct == 0){
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!");
correct = 1;
System.out.println("Would you like to play again? y/n");
playGame = scan.next().charAt(0);
}
// counter to keep running total of times guessed
guesses++;
System.out.println("You have guessed " + guesses + " times!");
}
}
干杯!
关于java - 猜谜游戏中的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57136432/
我是一名优秀的程序员,十分优秀!