user3563945
user3563945

Reputation: 29

Need to update a variable inside a while loop

I am trying to define a main method that asks the user for an input (x). If the value is >= 0, it asks for another input (y). But if the value was < 0 the player has three chances to enter a correct value, otherwise he exits the game. This is what I have until now:

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;
    }

But as I already defined 'x', I cannot do it again inside the loop. I think my problem is really simple but I cannot figure out a way to fix that. Does anyone know how?

Upvotes: 0

Views: 6075

Answers (2)

Bakon Jarser
Bakon Jarser

Reputation: 721

It looks like this might work if you just remove "int " from line 12. You don't need to declare the variable there since you have already declared it.

Upvotes: 1

user3389171
user3389171

Reputation: 161

If the condition to exit the loop is to enter a negative value 3 times, then use that as the actual condition. Code should be easier to read as well.

incorrectAttempts = 0;

while (incorrectAttempts < 3)
{

get new value

value invalid?
 yes: incorrectAttempts = incorrectAttempts + 1;
 no: do anything else;
}

Upvotes: 0

Related Questions