開關語句具有所謂的"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