We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello,
Say I need to sort a range of items, is there a way to do that using switch?
switch(num) {
case 1..60:
println("a");
break;
case 61..100:
println("b");
break;
case 101..109:
println("c");
break;
}
I can't seem to find a solution and would rather not have to use a bunch of if statements.
Thanks!
Tien
Answers
Inside
switch
, most we can do is chainedcase
:case 1: case 2: case 3: case 4: case 5: case 6: ... case 59: case 60: println("a"); break;
But we'd still have to type lotsa conditions anyways! :o3
switch/case
wasn't made for complex arrangements. For such, we gotta useif/else if/else
blocks! 8-|http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
If the value you're switching on is an int, you might also consider having a lookup array.
you could put the ranges into a separate function to prepare for switch
;-)
you can also use global consts to name the entries for case (and use them in the func and in switch) :
Thanks for the replies, everyone!
I think the easiest one for me now might be using TFGuy44.
No offense, but using a "lookup array" for mostly the same value is a pretty bad idea. You're much better off using basic if statements instead: