java
2015-12-04 31 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; 
相關問題