需要更新while循环中的变量

时间:2014-04-26 03:13:05

标签: java variables loops while-loop

我正在尝试定义一个主要方法,要求用户输入(x)。如果值>> = 0,则它要求另一个输入(y)。但是如果值是< 0玩家有三次机会输入正确的值,否则他退出游戏。这就是我现在所拥有的:

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',所以我不能在循环中再做一次。我认为我的问题非常简单,但我无法找到解决问题的方法。有谁知道怎么做?

2 个答案:

答案 0 :(得分:1)

如果你只是删除&#34; int&#34;这看起来可能会有用。从第12行开始。你不需要在那里声明变量,因为你已经声明了它。

答案 1 :(得分:0)

如果退出循环的条件是输入负值3次,则将其用作实际条件。代码也应该更容易阅读。

incorrectAttempts = 0;

while (incorrectAttempts < 3)
{

get new value

value invalid?
 yes: incorrectAttempts = incorrectAttempts + 1;
 no: do anything else;
}
相关问题