I found a few "somewhat" related questions on this, but I'm not confident that my needs have been fully qualified in those questions. So, what I'm looking to do is to clean up the following IF/ELSE IF statement with a SWITCH/CASE. Is there a way to use multiple conditional operators in a Java switch, or is it strictly Boolean?
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;
}
As Kon said, you can't simplify it into an incredibly simple switch/case, but you can do something like this:
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;
}
}
Which is fairly clean
You can only have a single expression in a case
clause. So no, you can't do it in the pretty way you are imagining.
See the Javadocs about switch
The closest thing you can do is something like:
switch (value)
{
case 1:
case 2:
//Operation if value is 1 or 2
break;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.