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

abs*_*son 5 java continue switch-statement

为什么是以下代码:

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

给出错误:

继续循环

Mic*_*yan 17

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

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

System.out.println("default");
if ( (a == 'a') || (a == 'b') ){
    System.out.println(a);
}
Run Code Online (Sandbox Code Playgroud)

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

编辑:不能在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);
    }
}
}
Run Code Online (Sandbox Code Playgroud)

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


ste*_*ase 7

continue语句来可以在循环中,而不是在交换机中使用.你可能想要的是一个break.


T.J*_*der 5

因为你有continue一个循环外面.continue用于跳回循环的开头,但是在该代码中没有任何循环.您想要打破switch案例块的是关键字break(见下文).

也没有必要将每个case块放在大括号内(除非你想要在其中包含本地范围的变量).

所以有点像这样会更标准:

class swi22
{
    public static void main(String[] args)
    {
        int a=98;
        switch(a)
        {
            default:
                System.out.println("default");
                break;
            case 'b':
                System.out.println(a);
                break;
            case 'a':
                System.out.println(a);
                break;
        }
        System.out.println("Switch Completed");
    }
}
Run Code Online (Sandbox Code Playgroud)

还有一种思想流派认为default条件应始终在最后.这不是一个要求,只是一个相当广泛使用的惯例.