Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading