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;
// ...
}
}