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?
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, ";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With