Skip to content
Advertisement

all of the condition are working except on the second else-if statement, how to correct this?

I am learning Java and I do not know what makes my code not reading my else-if condition (i == 5)

JavaScript

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.

JavaScript

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.

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement