Java: break statement in "if else"
Asked Answered
C

4

23

I keep getting an error, if without else.

I tried else if as well

for (;;) {
    System.out.println("---> Your choice: ");
    choice = input.nextInt();
    if (choice==1)
        playGame();
    if (choice==2)
        loadGame();
    if (choice==3)
        options();
    if (choice==4)
        credits();
    if (choice==5)
        System.out.println("End of Game\n Thank you for playing with us!");
        break;
    else
        System.out.println("Not a valid choice!\n Please try again...\n");
}

Also if you have a better idea on how to present this code please do not hesitate :)

Centner answered 18/12, 2013 at 23:42 Comment(3)
Java is not Python. You cant expect two lines to be in the same block just because they have the same indentation...Noonday
Even that won't solve the problem fully. All the if statements need to be connected with else.Kolb
Shouldn't it be: "else without if"?Biplane
M
20

Because your else isn't attached to anything. The if without braces only encompasses the single statement that immediately follows it.

if (choice==5)
{
    System.out.println("End of Game\n Thank you for playing with us!");
    break;
}
else
{
   System.out.println("Not a valid choice!\n Please try again...\n");
}

Not using braces is generally viewed as a bad practice because it can lead to the exact problems you encountered.

In addition, using a switch here would make more sense.

int choice;
boolean keepGoing = true;
while(keepGoing)
{
    System.out.println("---> Your choice: ");
    choice = input.nextInt();
    switch(choice)
    {
        case 1: 
            playGame();
            break;
        case 2: 
            loadGame();
            break;
        // your other cases
        // ...
        case 5: 
            System.out.println("End of Game\n Thank you for playing with us!");
            keepGoing = false;
            break;
        default:
            System.out.println("Not a valid choice!\n Please try again...\n");
     }
 }         

Note that instead of an infinite for loop I used a while(boolean), making it easy to exit the loop. Another approach would be using break with labels.

Mebane answered 18/12, 2013 at 23:47 Comment(1)
You want to make a note how to break out of the loop as break; in a switch will only break out of the switch.Deutzia
D
27

The "break" command does not work within an "if" statement.

If you remove the "break" command from your code and then test the code, you should find that the code works exactly the same without a "break" command as with one.

"Break" is designed for use inside loops (for, while, do-while, enhanced for and switch).

Dann answered 2/3, 2015 at 17:57 Comment(4)
The 'break' command does not work within an 'if' statement if that if statement is not within a control-structure loop/switch. I think that is where the confusion is? If its easier to grok, imagine using a 'continue' statement in a if statement.Chuddar
@erez this is old as yoink but Alan is correct in that the break statement does not break out of an IF statement. It beaks out of a loop, Basically, you said that's the wrong answer and then repeated what Alan said except worded differently. Alan did not mean that it doesn't run within an if, he meant that it doesn't break out of an if. Read the last part: "break" is designed for use inside loops (for, while, do-while, enhanced for, and switch)." Derp.Casimiracasimire
The break works in this case as it will break out the endless for(;;) loop.Piezochemistry
This is technically wrong. I know it's a few years late to point this out, but this is still relevant (and quite a fun tip to create messy code) in my opinion. You can use break anywhere - even without a loop, you just have to give it a label and reference that label. E.g test: if(someTest()) { doStuff(); if(!someOtherTest()) break test; }. To use it without a statement, you can just use a block: myBlock: { ...; break myBlock; }Buttonhook
M
20

Because your else isn't attached to anything. The if without braces only encompasses the single statement that immediately follows it.

if (choice==5)
{
    System.out.println("End of Game\n Thank you for playing with us!");
    break;
}
else
{
   System.out.println("Not a valid choice!\n Please try again...\n");
}

Not using braces is generally viewed as a bad practice because it can lead to the exact problems you encountered.

In addition, using a switch here would make more sense.

int choice;
boolean keepGoing = true;
while(keepGoing)
{
    System.out.println("---> Your choice: ");
    choice = input.nextInt();
    switch(choice)
    {
        case 1: 
            playGame();
            break;
        case 2: 
            loadGame();
            break;
        // your other cases
        // ...
        case 5: 
            System.out.println("End of Game\n Thank you for playing with us!");
            keepGoing = false;
            break;
        default:
            System.out.println("Not a valid choice!\n Please try again...\n");
     }
 }         

Note that instead of an infinite for loop I used a while(boolean), making it easy to exit the loop. Another approach would be using break with labels.

Mebane answered 18/12, 2013 at 23:47 Comment(1)
You want to make a note how to break out of the loop as break; in a switch will only break out of the switch.Deutzia
D
9

The issue is that you are trying to have multiple statements in an if without using {}. What you currently have is interpreted like:

if( choice==5 )
{
    System.out.println( ... );
}
break;
else
{
    //...
}

You really want:

if( choice==5 )
{
    System.out.println( ... );
    break;
}
else
{
    //...
}

Also, as Farce has stated, it would be better to use else if for all the conditions instead of if because if choice==1, it will still go through and check if choice==5, which would fail, and it will still go into your else block.

if( choice==1 )
    //...
else if( choice==2 )
    //...
else if( choice==3 )
    //...
else if( choice==4 )
    //...
else if( choice==5 )
{
    //...
}
else
    //...

A more elegant solution would be using a switch statement. However, break only breaks from the most inner "block" unless you use labels. So you want to label your loop and break from that if the case is 5:

LOOP:
for(;;)
{
    System.out.println("---> Your choice: ");
    choice = input.nextInt();
    switch( choice )
    {
        case 1:
            playGame();
            break;
        case 2:
            loadGame();
            break;
        case 2:
            options();
            break;
        case 4:
            credits();
            break;
        case 5:
            System.out.println("End of Game\n Thank you for playing with us!");
            break LOOP;
        default:
            System.out.println( ... );
    }
}

Instead of labeling the loop, you could also use a flag to tell the loop to stop.

bool finished = false;
while( !finished )
{
    switch( choice )
    {
        // ...
        case 5:
            System.out.println( ... )
            finished = true;
            break;
        // ...
    }
}
Deutzia answered 18/12, 2013 at 23:47 Comment(0)
P
0

Where some went there to provide alternative implementation of code the reason that the op code does not work is a missing {} pair;

    if (choice==5) {
        System.out.println("End of Game\n Thank you for playing with us!");
        break;
    } else
Piezochemistry answered 31/3, 2022 at 14:35 Comment(3)
You are putting up the same code the accepted answer gave 9 years ago, so what is the point here?Olson
missed that one, sorryPiezochemistry
Then just be honest about it, and delete your answer here. Dont wait for people to downvote and delete vote on it.Olson

© 2022 - 2025 — McMap. All rights reserved.