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?