我正在尝试制作一个程序,该程序接受最小和最大数字的输入,然后在该范围内生成一个随机数。然后用户猜测一个数字,如果它太高,它会输出一条消息。如果它太低,它会输出一条消息。我坚持的部分是当您正确猜测数字时,用户输入“Y”或“N”再次运行程序。
我的代码如下:
import java.util.Scanner;
import java.util.Random;
public class GuessingGame_V2
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print('\u000C');
int min;
int max;
int userGuess;
int numberGuesses = 1;
System.out.println("Enter the minimum number: ");
min = in.nextInt();
System.out.println("Enter the maximum number: ");
max = in.nextInt();
Random r = new Random();
int randomNumber = r.nextInt(max - min + 1) + min;
System.out.println("Enter your guess: ");
userGuess = in.nextInt();
String guessAgain = ("Y");
while(!guessAgain.equalsIgnoreCase("N"))
{
if( userGuess > randomNumber ){
System.out.println("Your guess was to high! Guess again!");
System.out.println("Input your new guess: ");
userGuess = in.nextInt();
numberGuesses++;
}
else if (userGuess < randomNumber ){
System.out.println("Your guess was to low! Guess again!");
System.out.println("Input your new guess: ");
userGuess = in.nextInt();
numberGuesses++;
}
else
{
System.out.println("Congratulations, you guessed the number!");
System.out.println("It took " + numberGuesses + " tries");
System.out.println("Guess another number? (Y/N)");
guessAgain = in.next();
}
}
System.out.println("Thank's for playing!");
}
}
当用户点击“Y”重新启动程序时,问题就出现了。它不会重新启动,只会再次显示最终消息。(打印语句、猜测次数和 Y/N)。当用户键入“Y”时,我需要重新启动程序
我是在网站上发帖的新手.. 如果我把代码搞砸了,请原谅我-提前感谢您的帮助-
*更改 - 2013 年 11 月 13 日 10:58 更改了代码以接受多个输入并继续接受输入,直到用户正确为止。