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

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

问题描述

switch语句基本上是if,elif,elif,elif,elif等.

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

为什么switch语句需要在其中打断,而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语句.控制流从切换块后的第一条语句继续. break语句是必需的,因为没有它们,切换块中的语句会掉入:匹配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天全站免登陆