为什么我不能在 Java 的 switch 语句中使用“continue”?

新手上路,请多包涵

为什么是下面的代码:

 class swi
{
    public static void main(String[] args)
    {
        int a=98;
        switch(a)
        {
            default:{ System.out.println("default");continue;}
            case 'b':{ System.out.println(a); continue;}
            case 'a':{ System.out.println(a);}
        }
        System.out.println("Switch Completed");
    }
}

给出错误:

在循环外继续

原文由 abson 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 731
2 个回答

失败是 switch 语句的标准行为,因此,在 switch 语句中使用 continue 是没有意义的。 continue 语句仅用于 for/while/do..while 循环。

根据我对你的意图的理解,你可能想写:

 System.out.println("default");
if ( (a == 'a') || (a == 'b') ){
    System.out.println(a);
}

我还建议您将默认条件放在最后。

编辑:不能在 switch 语句中使用 continue 语句并不完全正确。一个(最好有标签的) continue 语句是完全有效的。例如:

 public class Main {
public static void main(String[] args) {
    loop:
    for (int i=0; i<10; i++) {
        switch (i) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 9:
            continue loop;
        }

        System.out.println(i);
    }
}
}

这将产生以下输出:0 2 4 6 8

原文由 Michael Aaron Safyan 发布,翻译遵循 CC BY-SA 3.0 许可协议

continue 语句可以在循环中使用,而不是在开关中使用。您可能想要的是 break

原文由 stefanglase 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题