Why can#39;t I use #39;continue#39; inside a switch statement in Java?(为什么我不能在 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 语句中使用“继续"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我不能在 Java 的 switch 语句中使用“继续"?


基础教程推荐
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 降序排序:Java Map 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01