2015-04-02 39 views
3

我的代碼如下所示:進行切換的情況下執行以往的案例

switch(read.nextInt()){ 
     case 1: 
      //do "a" and print the result 
      break; 
     case 2: 
      //do "b" and print the result 
      break; 
     case 3: 
      //do "a" and print the result 
      //do "b" and print the result 
    } 

是否有另一種方式做到這一點並不簡單地複製裏面有什麼情況下1和2? 我剛開始我的畢業,所以我只能用字符串併爲此掃描儀,謝謝:)

回答

0

一個棘手的,IMO更具可讀性:

int nextInt = read.nextInt(); 
if (nextInt % 2 == 1) { // or if (nextInt == 1 || nextInt == 3) { 
    // do "a" and print the result 
} 
if (nextInt > 1) { 
    // do "b" and print the result 
} 
+0

也許我不允許創建方法,而且這個答案非常合適,謝謝 – 2015-04-02 21:53:12

2

定義兩種方法稱爲doA()doB()並給他們打電話。這樣你就不會複製你的代碼。您是否確定在每個case聲明後不需要break聲明?

switch(read.nextInt()){ 
     case 1: 
      doA(); 
      break; 
     case 2: 
      doB(); 
      break; 
     case 3: 
      doA(); 
      doB(); 
      break; 
     default: 
      // do something 
      break; 
    } 
+0

我忘了寫,但是在我的代碼中有break語句,謝謝! – 2015-04-02 21:39:59

+0

更新了代碼。有一個默認情況也是一個很好的做法。 – 2015-04-02 21:40:49

0

在這樣的情況下,它可能是有道理爲

//do "a" and print the result 

//do "b" and print the result 

創建方法如果3你只需調用這些方法一前一後。

0

您好像忘了 '休息'。它使switch語句中的代碼「中斷」。如果你在「1」 &「2」做同樣的事情,在「3」的其他東西的情況下的情況下想,你可以寫:

switch(read.nextInt()){ 
     case 1: 
     case 2: 
      //do "a" or "b" and print the result 
      break; //break from switch statement, otherwise, the code below (yes, I mean "case 3") will be executed too 
     case 3: 
      //do "a" and print the result 
      //do "b" and print the result 
    } 

這是加入「破發」,在一個平常的事情如果你不想讓相同的代碼塊被執行幾個值,那麼「case」塊的結尾:

switch(n){ 
     case 1: 
      //do something 
      break; 
     case 2: 
      //do other things 
      break; 
     case 3: 
      //more things! 
      //you may not write "break" in the last "case" if you want 
    } 
相關問題