Search code examples
javaswitch-statementuppercaselowercase

How can I access the case of a switch with two conditions in java?


I'm making a program with a menu where the user is asked to select an option labeled by letters:

a) option 1

b) option 2

c) option 3

...

Select an option:

The program needs to be case insensitive so lowercase and uppercase are both accepted. I want to make a switch to organize the different options but as it is case insensitive, do I need to convert the option to lowercase or uppercase or is there an option to enter the case independently of it's lower or upper?


Solution

  • You could use multiple case expressions for the upper and lower cases:

    switch (input) {
        case "a":
        case "A":
            doA();
        case "b":
        case "B":
            doB();
        case "c":
        case "C":
            doC();
    }
    

    But as you can see, this gets really clunky really fast. Converting everything to lowercase (or uppercase, if you prefer) seems a lot simpler:

    switch (input.toLowerCase()) {
        case "a":
            doA();
        case "b":
            doB();
        case "c":
            doC();
    }