Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

like image 709
Gavin Faulkner Avatar asked Feb 23 '13 21:02

Gavin Faulkner


2 Answers

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.

like image 194
Makoto Avatar answered Oct 12 '22 01:10

Makoto


Use the fall-through case:

case "England":
case "UK":
    return "Hallo, ";
like image 34
Reimeus Avatar answered Oct 12 '22 01:10

Reimeus