简体   繁体   中英

Can you have two comparisons in one case statement in a switch?

I was just wondering if I could have two strings I can test for on one case in a switch statement. For example:

     switch (month){
        case "Jan": ...

     }

This is a regular switch statement, but is there any way to implement a way to compare two strings such as:

    switch (month){
       case "Jan" || "January": ....
    }

I wanted to know if there is a way to implement this sort of method of code, where I can test for Jan OR January.

Not directly. Instead let execution flow through the case s

switch (month){
    case "Jan":
    case "January": 
        ...
}

If month equals "Jan " it will hit that case and flow into the "January" case.

It doesn't seem like you really understood Sotirios's answer. Here's a longer example:

switch (month) {
    case "Jan":
    case "January":
        System.out.println("It's January!");
        // Do whatever else
        break;
    case "Feb": case "February": // They can even go on the same line
        System.out.println("It's February!");
        // Do whatever else
        break;
    ...
}

This is almost exactly the same in terms of "code room" as your example, except you have to have to repeat the case keyword.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM