0

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?

1
  • Your question doesn't really make sense. Why are you worried about redefining 'x'? What is the problem? Error message? Unexpected output? Commented Apr 26, 2014 at 3:16

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.