在“ if else”中的break语句-Java [英] break statement in "if else" - java

查看:647
本文介绍了在“ if else”中的break语句-Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不断收到错误消息,如果没有 则没有错误,

I keep getting an error, if without else.

我也尝试了否则

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
    }

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

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

推荐答案

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

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

请注意,不是无限的对于循环,我使用了 while(boolean),可以轻松退出循环。另一种方法是使用带有标签的中断。

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.

这篇关于在“ if else”中的break语句-Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆