为什么 java 在 switch 语句中需要中断? [英] Why does java require a break inside a switch statement?

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

问题描述

switch 语句基本上是 if、elif、elif、elif、elif、else.

A switch statement is basically a if, elif, elif, elif, elif, else.

为什么 switch 语句需要一个 break 而 else if 语句不需要?有什么区别?

Why does a switch statement need a break within it and an else if statement doesnt? What is the difference?

如果,否则如果不需要休息.

If, else if doesn't require a break.

if (c = 'a'){
     System.out.println("");
}
else if (c = 'b'){
     System.out.println("");
}

Switch 语句需要中断.

Switch statement requires a break.

switch(c){
case('a'){
     System.out.println("");
     break;}
case('b'){
     System.out.println("");
      break;}
}

推荐答案

你必须在每个案例中添加 break,例如

You have to add break to each case, e.g.

switch(choice){
   case 1:
     System.out.print("haha");
     break;
   case 2:
     System.out.print("aloha");  
     break;
}

每个 break 语句都会终止封闭的 switch 语句.控制流继续 switch 块之后的第一条语句.break 语句是必要的,因为没有它们,switch 块中的语句就会失败:匹配的 case 标签之后的所有语句都按顺序执行,无论后续 case 标签的表达式如何,直到遇到 break 语句.

Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.

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

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