gpt4 book ai didi

java - 猜谜游戏中的随机数

转载 作者:行者123 更新时间:2023-12-02 02:47:07 24 4
gpt4 key购买 nike

我正在尝试编写一个猜数游戏程序,因此程序会生成一个随机数,并且程序会提示太高、太低,直到用户得到它的写入。然而,随机生成器要么每次生成相同的随机数,要么对于一个用户输入说“太高”,然后对紧接着/之后的用户输入说“太低”

我已将随机生成器移至 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com