I am learning Java and I do not know what makes my code not reading my else-if condition (i == 5)
int i; for (i = 1; i <= 5; i++) { int guess = scanner.nextInt(); System.out.println("Attempt: " + i +"/5"); if (guess < numberToGuess) { System.out.println("Higher"); } else if (guess > numberToGuess) { System.out.println("Lower"); } else if (i == 5) { System.out.println("You failed! The correct answer is " + numberToGuess); } else { System.out.println("You won! Your answer is " + numberToGuess + " which is correct!"); break; }
when i’m running the code and try to fail the game by reaching the maximum number of int i which is 5, the second else if statement should appear but it is not working.
I just don’t get the reason why it is not reading the (i==5) condition, all of the other conditions are working except that.
Advertisement
Answer
Well, if-else statements work like this: when any one of the statements are satisfied, the rest of them are ignored. Take yours as an example.
if (guess < numberToGuess) { System.out.println("Higher"); } else if (guess > numberToGuess) { System.out.println("Lower"); } else if (i == 5) { System.out.println("You failed! The correct answer is " + numberToGuess); } else { System.out.println("You won! Your answer is " + numberToGuess + " which is correct!"); break; }
Even when i == 5
, if either of guess < numberToGuess
or guess > numberToGuess
are satisfied, the rest of the statements including (i == 5)
are ignored.
To fix this, simply add i == 5
as the first condition to check, because if i == 5
is satisfied we shouldn’t be considering the guess anyway.
I’m also guessing you want to break out of the loop if the game ends, so I added a break
statement as well.
if (i == 5) { System.out.println("You failed! The correct answer is " + numberToGuess); break; } else if (guess < numberToGuess) { System.out.println("Higher"); } else if (guess > numberToGuess) { System.out.println("Lower"); } else { System.out.println("You won! Your answer is " + numberToGuess + " which is correct!"); break; }