dwwilson66 dwwilson66 - 7 months ago 12
Java Question

Can I use a range of values in a single switch?

I'm trying to simplify a Card class, and am wondering if there's any way to use a range of values in a switch statement?

CONSIDER:

if((card<14))
suit="Hearts";
else
if((card>14)&&(card<27))
suit="Clubs";

etc.


Instead I'd like to use a switch statement, such as:

switch(card){
case1: through case13:
suit="Hearts";
break;

etc.


I wasn't able to find anything in the Java Tutorials that suggest there is such a variation of switch. But is there?

dcp dcp
Answer

About the best you can do is something like this (see below). So in some cases (no pun intended :)), it's just better to use an if statement.

switch(card){
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
    case 6:
    case 7:
    case 8:
    case 9:
    case 10:
    case 11:
    case 12:
    case 13:
        suit="Hearts";
        break;
}

However, another approach you could consider is using a map.

Map<Integer, String> map = new HashMap<Integer, String>();
for (int i = 1; i <= 14; ++i) {
  map.put(i, "Hearts");
}
for (int i = 15; i <= 26; ++i) {
  map.put(i, "Clubs");
}

Then you can look up the card's suit using the map.

String suit1 = map.get(12); // suit1 will be Hearts after the assignment
String suit2 = map.get(23); // suit2 will be Clubs after the assignment