当前位置:首页 > 芯闻号 > 充电吧
[导读]public class Test7 { public static void main(String[] args) {  int i=5;  switch(i)  {    case 1:   S


public class Test7 {

 public static void main(String[] args)
 {
  int i=5;
  switch(i)
  {
  
  case 1:
   System.out.println("one");
   
  case 10:
   System.out.println("ten");
   
  case 5:
   System.out.println("five");
   
  case 3:
   System.out.println("three");
   
  default:
   System.out.println("other");
  }
 }
}
为什么结果是:
five
three
other

而没有one和ten,这是为什么呢?

switch(表达式)
{
case 常量表达式1:语句1;
....
case 常量表达式2:语句2;
default:语句;
}
switch的用法是判断case后面的表达式和switch后面的表达式是否相匹配,一旦case匹配,就会顺序执行后面的程序代码,而不管后面的case是否匹配,直到遇见break。
在你所给的代码中,由于i等于5,和前面的两个case都不匹配,所以结果中并没有one和ten的。而第三个case中的5就和switch中i的值匹配,因此就会打印出five的,由于没有遇到break所以就会顺序执行很面的代码,打印出three和other





本站声明: 本文章由作者或相关机构授权发布,目的在于传递更多信息,并不代表本站赞同其观点,本站亦不保证或承诺内容真实性等。需要转载请联系该专栏作者,如若文章内容侵犯您的权益,请及时联系本站删除( 邮箱:macysun@21ic.com )。
换一批
延伸阅读
关闭