Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a switch case execute previous cases

My code looks like:

    switch(read.nextInt()){
        case 1:
            //do "a" and print the result
            break;
        case 2:
            //do "b" and print the result
            break;
        case 3:
            //do "a" and print the result
            //do "b" and print the result
    }

Is there another way to do it without simply copying what's inside case 1 and 2? I just started my graduation, so I can only use String and Scanner for this, thanks :)

like image 923
João Oliveira Avatar asked Mar 02 '26 21:03

João Oliveira


1 Answers

Define two methods called doA() and doB() and call them. This way you won't duplicate your code. Also are you sure you don't need break statements after each case statement?

    switch(read.nextInt()){
        case 1:
            doA();
            break;
        case 2:
            doB();
            break;
        case 3:
            doA();
            doB();
            break;
        default:
            // do something
            break;
    }

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!