开关语句具有所谓的"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;
因为没有'打破;' – Tunaki
阅读[Java教程:在'之开关声明】(http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html) – Barranka
@Tunaki你的意思是什么没有休息?就像情况A,B和C一样,D从哪里来?如果交换机没有发现任何情况,这是否意味着默认输出x? – Rabin