简体   繁体   中英

Using “||” in switch statements in java

Part of a Java program I'm making asks the user their home country. Another part uses a switch statement, and I get an error. The error is: The operator || is undefined for the argument type(s) java.lang.String, java.lang.String The operator || is undefined for the argument type(s) java.lang.String, java.lang.String . Here's the method where the problem occurs:

public static String getCountryMessage(String countryName) {
    switch (countryName) {
    case "USA":
        return "Hello, ";
    case "England" || "UK":
        return "Hallo, ";
    case "Spain":
        return "Hola, ";
    case "France":
        return "Bonjour, ";
    case "Germany":
        return "Guten tag, ";
    default:
        return "Hello, ";
    }
}

How does one use && and || in a Java switch statement?

I don't think you can use conditionals like that in switch statements. It'd be simpler and more straightforward to write this instead:

case "England":
case "UK":
    return "Hallo";

This is a fall-through case - if your string matches either England or UK, it will return Hallo .

Use the fall-through case:

case "England":
case "UK":
    return "Hallo, ";

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