“if else”中的break语句 - java

时间:2013-12-18 23:42:54

标签: java if-statement for-loop infinite-loop break

我一直收到错误,if没有else

我也试过了else if

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");=[;'mm
    }

如果您对如何呈现此代码有更好的了解,请不要犹豫:)

3 个答案:

答案 0 :(得分:13)

"休息"命令不能在" if"言。

如果您删除" break"从你的代码命令,然后测试代码,你会发现代码工作完全相同没有" break"命令与一个。

"分段"设计用于内部循环(for,while,do-while,增强和切换)。

答案 1 :(得分:12)

因为您的else没有附加任何内容。没有大括号的if仅包含紧随其后的单个语句。

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");
}

不使用大括号通常被视为一种不好的做法,因为它可能会导致您遇到的确切问题。

此外,在这里使用switch会更有意义。

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");
     }
 }         

请注意,我使用了for而不是无限while(boolean)循环,因此可以轻松退出循环。另一种方法是使用break with labels。

答案 2 :(得分:5)

问题是您尝试在if中使用多个语句而不使用{}。 你现在拥有的东西被解释为:

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

你真的想要:

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

此外,正如Farce所说,最好将else if用于所有条件,而不是if,因为如果choice==1,它仍会检查choice==5是否if( choice==1 ) //... else if( choice==2 ) //... else if( choice==3 ) //... else if( choice==4 ) //... else if( choice==5 ) { //... } else //... 1}},这会失败,它仍会进入你的其他区块。

switch

更优雅的解决方案是使用break语句。但是,除非您使用标签,否则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( ... ); } } 仅从最内部的“块”中断开。所以你想标记你的循环,如果情况是5,那就打破它:

bool finished = false;
while( !finished )
{
    switch( choice )
    {
        // ...
        case 5:
            System.out.println( ... )
            finished = true;
            break;
        // ...
    }
}

除了标记循环外,您还可以使用一个标志来告诉循环停止。

{{1}}
相关问题