我正在尝试定义一个询问用户输入(x)的主要方法。如果该值大于等于0,它会要求另一个输入(y)。但是,如果该值为< 0,则玩家有三次机会输入正确的值,否则他退出游戏。这是我到现在为止:需要更新while循环中的变量
Scanner keyboard = new Scanner(System.in);
final int NUMBER_OF_TRIES = 3;
boolean correctNumber = false;
int attemptNumber = 0;
int x = keyboard.nextInt();
keyboard.nextLine();;
while (x < 0)
{
System.out.println("Must not be negative.");
System.out.print("Initial x: ");
int x = keyboard.nextInt(); keyboard.nextLine();
if (x >= 0)
{
correctNumber = true;
}
else
{
System.out.println("Incorrect answer");
attemptNumber++;
}
if(x < 0 && attemptNumber == NUMBER_OF_TRIES)
{
System.out.println("Too many errors. Exiting.");
break;
}
但正如我已经定义的“X”,我不能再这样做内循环。我认为我的问题非常简单,但我找不出解决该问题的方法。有谁知道如何?
你的问题没有意义。你为什么担心重新定义'x'?问题是什么?错误信息?意外的输出? – Daniel