仅当输入为“true”或“false”时才将字符串转换为布尔值

1 java string boolean type-conversion

如何确保字符串的输入是“真”或“假”,然后将其解析为布尔值?

例如:

String input = "true"; -> boolean result = true;
String input = "false"; -> boolean result = false;
String input = "foobar"; -> throw new InvalidInputException("true or false is allowed");
Run Code Online (Sandbox Code Playgroud)

tom*_*ty3 6

if else如果您想绝对确保输入是“真”/“真”或“假”/“假”,则必须进行陈述:

if ("true".equalsIgnoreCase(input) {
    return true;
} else if ("false".equalsIgnoreCase(input)) {
    return false;
} else {
    throw new InvalidInputException("true or false is allowed")
}
Run Code Online (Sandbox Code Playgroud)

如果您实际上只想要区分大小写的“true”或“false”,则更.equalsIgnoreCase()改为.equals()

或者,您可以BooleanUtils在 Apache Commons Lang https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/BooleanUtils.html 中使用

 Boolean bool = BooleanUtils.toBooleanObject(input)
Run Code Online (Sandbox Code Playgroud)

如果它既不是“真”也不是“假”(其中包括“t”、“y”、“是”等 - 请参阅 JavaDoc)然后null返回

  • 如果您将字符串的顺序与“true”.equalsIgnoreCase(input) 进行比较,则不需要这些空检查。 (2认同)