Is it possible to have ranges in switch() and case?

edited February 2014 in Questions about Code

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

Tagged:

Answers

  • edited February 2014 Answer ✓

    Inside switch, most we can do is chained case:

    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 use if/else if/else blocks! 8-|

    http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

  • edited February 2014 Answer ✓

    If the value you're switching on is an int, you might also consider having a lookup array.

    String[] lookup = {"a","a","a",...,"b","b",...,"c"}
    println(lookup[num]);
    
  • edited February 2014 Answer ✓

    you could put the ranges into a separate function to prepare for switch

    ;-)

        int valueForSwitch = funcMapValueForSwitch (num);
    
        switch (valueForSwitch) {
    
       case 0:
       //
       break;
    
       case 1:
       // 
       break;
    
       case 2:
       // 
       break;
    
       case -1:
       // do nothing 
       break;  
    
       default:
       // error 
       println ("error code 967");
       break; 
    
        }
    
        ...
    
        int  funcMapValueForSwitch ( int numLocal ) {
        if (numLocal>=1 && numLocal <= 60) return 0;
        if (numLocal>=61 && numLocal <= 100) return 1;
        if (numLocal>=101 && numLocal <= 109) return 2;
        // default : 
        return -1;
        }
    

    you can also use global consts to name the entries for case (and use them in the func and in switch) :

    final int rangeIs1_60 = 0;
    final int rangeIs61_100 = 1;
    final int rangeIs101_109 = 2;
    final int rangeIsUnknown = -1; 
    
  • 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:

    if(num >= 1 && num < 60) {
        println("a");  
    }
    else if(num <100){
        println("b");  
    }
    else if(num < 109){
        println("c");  
    }
    
Sign In or Register to comment.