java
2015-12-04 30 views -1 likes 
-1

为什么输出"ADC"D来自哪里?此外,此代码中的defaultcontinue命令的目标是什么?eclipse上的开关

char x = 'A'; 
while(x != 'D') { 
    switch(x) { 
    case 'A': 
     System.out.print(x); x = 'D'; 
    case 'B': 
     System.out.print(x); x = 'C'; 
    case 'C': 
     System.out.print(x); x = 'D'; 
    default: 
     continue; 
} 
+8

因为没有'打破;' – Tunaki

+1

阅读[Java教程:在'之开关声明】(http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html) – Barranka

+0

@Tunaki你的意思是什么没有休息?就像情况A,B和C一样,D从哪里来?如果交换机没有发现任何情况,这是否意味着默认输出x? – Rabin

回答

3

您从A开始。由于x != 'D'您输入while循环。
现在的流动如下:

  • 输入case 'A'
  • 打印A和分配x = 'D'
  • 落空到case 'B'
  • 打印D(因为x == 'D')和分配x = 'C'
  • fall-到case 'C'
  • 打印C(因为x == 'C'),并指定x = 'D'
  • 下通到default(这通常会达到,当你无法找到匹配的case
  • continue(这意味着回归while循环的开始)
  • 由于x == 'D'条件评估为false并且不会进入循环。

==>结果:打印出ADC

2

是的,你忘了步骤之间的break s。因此,匹配案例之后的所有步骤都将被执行。

switch (x) { 
    case 'A': 
     System.out.print(x); 
     x = 'D'; 
     break; 
    case 'B': 
     System.out.print(x); 
     x = 'C'; 
     break; 
    case 'C': 
     System.out.print(x); 
     x = 'D'; 
     break; 
} 
1

看看这个开关:与尝试它

int a = 0; 
switch(a) { 
case 0: 
    System.out.println("0"); 
case 1: 
    System.out.println("1"); 
} 

被执行的代码行是:

  1. int a = 0;
  2. System.out.println("0");
  3. System.out.println("1");

为了只执行要执行你必须在每一种情况下结束使用break声明:

int a = 0; 
switch(a) { 
case 0: 
    System.out.println("0"); 
    break; 
case 1: 
    System.out.println("1"); 
    break; 
} 
1

当第一次开关执行,情况“A”选中,画的并集x到'D', 案例之间没有中断,所以下一行执行 - 打印D(因为x先前设置为'D')并将x设置为'C'。等等。

2

开关语句具有所谓的"fall through"

你需要一个break在每个案件的结尾,否则所有的人都会运行,就像这里发生的一样。

char x = 'A'; //starts off as A 
while(x != 'D') { 
    switch(x) { 
    case 'A': 
     System.out.print(x); x = 'D'; //here is gets printed and changed to D 
    case 'B': //you fall through here because there's no break 
     System.out.print(x); x = 'C'; //print again then change to C 
    case 'C': //fall through again 
     System.out.print(x); x = 'D'; //print again then change to D 
    default: 
     continue; 

是否匹配(所以如果它开始为C,将只打印一次),但一旦找到匹配,您可以通过掉在其他情况下,以及你只输入case

如果你添加break s,那么你就不会再经历了。

char x = 'A'; 
while(x != 'D') { 
    switch(x) { 
    case 'A': //match 
     System.out.print(x); x = 'D'; //print then modify 
     break; //break 
    case 'B': 
     System.out.print(x); x = 'C'; 
     break; 
    case 'C': 
     System.out.print(x); x = 'D'; 
     break; 
    default: 
     continue; 
相关问题