简体   繁体   English

在java中的switch语句中使用“||”

[英]Using “||” in switch statements in java

Part of a Java program I'm making asks the user their home country. 我正在制作Java程序的一部分,询问用户他们的祖国。 Another part uses a switch statement, and I get an error. 另一部分使用switch语句,我收到错误。 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 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? 在Java switch语句中?

I don't think you can use conditionals like that in switch statements. 我不认为你可以在switch语句中使用这样的条件。 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 . 这是一个落空案例 - 如果你的字符串匹配英格兰或英国,它将返回Hallo

Use the fall-through case: 使用坠落案例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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