javaswitch-statement

java switch statement many cases simplified


So lets say a switch statment is,

switch (month) {  
    case 1: monthString = "January";  
        break;  
    case 2: monthString = "February";  
        break;  
    case 3: monthString = "March";  
        break;  
    case 4: monthString = "April";  
        break;  
    case 5: monthString = "May";  
        break;  

Is it possible to shorten that to something like

switch (month) {
    cases 1-3: monthString = "January";
        break;
    case 4-5: monthString = "April";
        break;

So that multiple case numbers are under one case? I'm doing it as I have 100 cases. 30 lead to one answer, 20 to another, 5 to another etc... so if I can use multiple cases I should cut down the bulk of the code by alot. I should also mention at each case I will want to do a few things and if I use a series of if else statements it only lets me perform one action so I cannot seem to go that route. Thanks for any help! sorry I'm new at this!


Solution

  • Is it possible to shorten that to something like

    It's better explained in Java Tutorial The switch Statement

    Yes you can do it.

    Some of the key points:

    sample code:

        int month = 1;
        String monthString = null;
    
        switch (month) {
            case 1:
            case 2:
            case 3:
                monthString = "January";
                break;
            case 4:
            case 5:
                monthString = "April";
                break;
            ...
            default:
                ...
        }