1

first I'd like to apologize for the weird question, I'm quite new to Java.

So, let's say I had a piece of code like this here:

    switch(test) {

        case 50:
        case 51:
        case 52:
        case 53:
        case 54:
        case 55:
        case 56:
        case 57:
        case 58:
        case 59:
        case 60:
        case 61:
        case 62:
        case 63:
        case 64:
        case 65:
        case 66:
        case 67:
        case 68:
        case 69:
        case 70:
        case 71:
        case 72:
        case 73:
        case 74:
        case 75:
        case 76:
        case 77:
        case 78:
        case 79:
        case 80:
            System.out.println("random");


        }
        break;

Just for example.

There's quite a lot of cases and I'm wondering if there's a way to shorten it. I tried using a for loop to iterate through this data but I couldn't quite wrap my head around it. Any help is appreciated.

Again, excuse the nooby question! I'm quite new to Java!

Thanks in advance.

  • 1
    I think you should post some of the Java code contained in those `switch` statements. As is, I don't think we can remove any cases without more information. – Tim Biegeleisen Sep 10 '15 at 03:29
  • No this was completely example code. It has nothing to do with anything I need to remove. I'm simply asking if there's anyway to shorten it by iterating through those integers and having 1 case instead of 30. – andrewDev15 Sep 10 '15 at 03:31

3 Answers3

5
  • If you have 20+ different cases to deal with you have to deal with them. No other option.
  • And a small gotcha will be, if you have same task for different cases, you can do what you are doing, like single task for multiple cases.

And answer for your particular case, you can write

if(yourSwitchParam >= 50 && yourSwitchParam <=80 ){
   System.out.println("random");
}

Add this conditions on top of switch. If you have any further logic, have switch on them.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
3

If all of those cases execute the same statement then you could use a default statement to catch the general case. Or convert your switch statement to an if statement:

if (test >= 50 && test <= 80) {
    ...
}

In general it's a good idea to avoid switch statements. They make maintenance difficult as they usually require you to add options in several places which can lead to errors that are hard to detect. There are some specific situations in which they are good practice but they are not common. A good alternative is to define an enum where the members of the enum dictate the behaviour for that member.

sprinter
  • 27,148
  • 6
  • 47
  • 78
1

If you are only looking for a key/value relationship, you could statically initialize a HashMap with the numbers and look them up in constant time. Other tests that iterate will have O(n) complexity.

Clayton Wilkinson
  • 4,524
  • 1
  • 16
  • 25