为什么我不能在Java中的switch语句中使用'continue'? [英] Why can't I use 'continue' inside a switch statement in Java?

查看:1711
本文介绍了为什么我不能在Java中的switch语句中使用'continue'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么会出现以下代码:

Why is it that the following code:

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

给出错误:


继续循环之外

continue outside of loop


推荐答案

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

Falling through is the standard behavior for a switch statement and so, consequently, using continue in a switch statement does not make sense. The continue statement is only used in for/while/do..while loops.

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

Based on my understanding of your intentions, you probably want to write:

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

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

I would also suggest that you place the default condition at the very end.

编辑:
在switch语句中不能使用continue语句。 (理想标记的)继续语句完全有效。例如:

It is not entirely true that continue statements cannot be used inside switch statements. A (ideally labeled) continue statement is entirely valid. For example:

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

This will produce the following output: 0 2 4 6 8

这篇关于为什么我不能在Java中的switch语句中使用'continue'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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