2015-02-06 91 views
1

我發現了一些「有點」相關的問題,但我不確定我的需求是否完全符合這些問題。所以,我期望做的是用SWITCH/CASE清理以下IF/ELSE IF語句。有沒有辦法在Java開關中使用多個條件運算符,還是嚴格布爾值?Java開關 - 不同條件運算符

int alSize = Integer.parseInt(size); 

if (alSize == 7 && (alType == 1 || alType == 3)){ 
disp = 0.12; 
}else if (alSize == 9 && (alType == 1 || alType == 3 || alType == 4 || alType == 5)){ 
disp = 0.27; 
}else if (alSize == 9){ 
disp = 0.21; 
}else if (alSize == 11 && (alType == 1 || alType == 3 || alType == 4 || alType == 5)){ 
disp = 0.47; 
}else if (alSize == 11){ 
disp = 0.41; 
}else if (alSize == 12 && (alType == 1 || alType == 3 || alType == 4 || alType == 5)){ 
disp = 0.75; 
}else if (alSize == 12){ 
disp = 0.64; 
}else if (alSize == 14 &&(alType == 1 || alType == 3 || alType == 4 || alType == 5)){ 
disp = 1.10; 
}else if (alSize == 14){ 
disp = 0.96; 
}else if (alSize == 16 && (alType == 1 || alType == 3 || alType == 4 || alType == 5)){ 
disp = 1.60; 
}else if (alSize == 16){ 
disp = 1.40; 
}else if (alSize == 18 && (alType == 1 || alType == 3 || alType == 4 || alType == 5)){ 
disp = 2.60; 
}else if (alSize == 18){ 
disp = 2.30; 
}else if (alSize == 22 && (alType == 1 || alType == 3 || alType == 4 || alType == 5)){ 
disp = 4.0; 
}else if (alSize == 22){ 
disp = 3.60; 
}else if (alSize == 30 && (alType == 1 || alType == 3 || alType == 4 || alType == 5)){ 
disp = 9.9; 
}else if (alSize == 30){ 
disp = 9.2; 
} 
+0

我VOT只是因爲這個陳述是如此......哇。 – 2015-02-06 01:11:32

回答

4

的kon說,你不能把它簡化成一個非常簡單的開關/箱,但你可以做這樣的事情:

boolean typeIs1345 = (alType == 1 || alType == 3 || alType == 4 || alType == 5); 

    switch (alSize) 
    { 
     case 7: 
      if (alType == 1 || alType == 3) 
       disp = 0.12; 
      break; 
     case 9: 
      disp = typeIs1345 ? 0.27 : 0.21; 
      break; 
     case 11: 
      disp = typeIs1345 ? 0.47 : 0.41; 
      break; 
     case 12: 
      disp = typeIs1345 ? 0.75 : 0.64; 
      break; 
     case 14: 
      disp = typeIs1345 ? 1.1 : 0.96; 
      break; 
     case 16: 
      disp = typeIs1345 ? 1.6 : 1.4; 
      break; 
     case 18: 
      disp = typeIs1345 ? 2.6 : 2.3; 
      break; 
     case 22: 
      disp = typeIs1345 ? 4.0 : 3.6; 
      break; 
     case 30: 
      disp = typeIs1345 ? 9.9 : 9.2; 
      break; 
    } 
} 

這是相當乾淨

+0

這種方式更清潔...謝謝你! – jbeckom 2015-02-06 01:21:22

0

case子句中只能有一個表達式。所以不,你不能用你想象中的美麗方式去做。

請參閱Javadoc約switch

你可以做的最接近的事是一樣的東西:

switch (value) 
    { 
     case 1: 
     case 2: 
      //Operation if value is 1 or 2 
     break; 
    }