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

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

问题描述

为什么是下面的代码:

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

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

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