为什么我不能在 Java 的 switch 语句中使用“继续"?

2022-01-19 00:00:00 switch-statement java 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");
    }
}

给出错误:

在循环外继续

推荐答案

失败是 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 语句并不完全正确.(理想标记的)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);
    }
}
}

这将产生以下输出:02468

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

相关文章