I'm looking to make a switch where 5 of the cases are functionally identical, but then th开发者_StackOverflow中文版ere will be other unique cases. Is there a way to list a case value that handles 5 different values? Thanks
You can compound the labels in the switch
switch (variable) {
case 'a': case 'b' : case 'c' : case 'd' :
do something;
break;
case 'e': case 'f' :
do something else
break;
default:
do something;
}
Thinking of a switch as a jump to a label (possibly coupled with a jump (the break) to the end) will help. That means the switch
switch (variable) {
case 'a': case 'b' : case 'c' : case 'd' :
do something;
// note that there's no break here.
case 'e': case 'f' :
do something else
break;
default:
do something;
}
will "do something" and "do something else" for 'a', 'b', 'c', and 'd'; while it will only "do something else" for 'e' and 'f'. Finally if it's not any of the above it hits the default block of "do something".
switch (value) {
case 1:
case 2:
case 3:
case 4:
doSomethingIdentical();
break;
case 5:
doSomethingDifferent();
break;
default:
break;
}
This is very easy to do. Instead of just having one case value that handles all 5 different values, let the 5 case values fall through to each other, like so:
switch(value)
{
case 1:
case 2:
//case 1 and 2 will both result in this code being executed
doSomething();
break;
case 3:
doSomethingElse();
break;
}
As long as you don't put a break;
on a switch it will fall through to the next statement.
In that way, you can have something like this:
String value(int val) {
String out = "";
switch(val) {
case 0:
out = "case 0";
break;
case 1:
out = "case 1";
break;
case 2:
case 3:
case 4:
case 5:
case 6:
out = "case 2, 3, 4, 5 or 6";
break;
case 7:
out = "case 7";
break;
}
return out;
}
Yes, just use a switch like this:
switch(v) {
case 1:
case 2:
case 3:
identicFunctionality();
break;
case 4:
other01();
break;
case 5:
other02();
break;
default:
_default();
}
As of Java 12 I believe it is supported. Check out JEP 354. I have never used the syntax but I think it would run like this for your case.
switch (day) {
case 1, 2, 3, 4, 5 -> System.out.println("1-5");
case 7 -> System.out.println(7);
case 8 -> System.out.println(8);
case 9 -> System.out.println(9);
}
on a related note JEP 325 is also cool.
精彩评论