Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 603
Dodo Avatar asked Mar 13 '26 04:03

Dodo


1 Answers

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:

  • Don't forget to add the break statement.
  • Add single break statement after all grouped cases.
  • Never forget to add default case as well.

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:
            ...
    }
like image 69
Braj Avatar answered Mar 15 '26 19:03

Braj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!