java-me:将String转换为boolean

Jos*_*e S 14 string blackberry java-me

我正在为BlackBerry开发,我遇到了这个愚蠢的问题:

我需要将字符串值"1"和"0"分别转换为true和false.尽管如此,Blackberry JDK基于Java 1.3,因此我不能使用Boolean.parseBoolean,Boolean.valueOf或Boolean.getValue.

显然我可以这样做:

if (str.equals("1")) return true;
else if (str.equals("0")) return false;
Run Code Online (Sandbox Code Playgroud)

但这看起来非常难看,也许这些字符串值可能会在以后变为"true"和"false".那么,有没有另一种方法来转换这些类型(String - > boolean,Java 1.3)?

更新:这个问题的所有答案都非常有用,但我需要标记一个,所以我选择了Ishtar的答案.

即便如此,我的修复是多个答案的组合.

Ish*_*tar 14

public static boolean stringToBool(String s) {
  if (s.equals("1"))
    return true;
  if (s.equals("0"))
    return false;
  throw new IllegalArgumentException(s+" is not a bool. Only 1 and 0 are.");
}
Run Code Online (Sandbox Code Playgroud)

如果您以后将其更改为"真/假",则不会意外订购28,000吨煤.使用错误的参数调用将抛出异常,而不是猜测并返回false.在我看来"pancake"不是false.


Bri*_*ach 9

如果你没有Boolean.valueOf(String s)...是的,那就是它.我定义了你自己的静态方法,如:

public static boolean booleanFromString(String s)
{
    return s.equals("1");
}
Run Code Online (Sandbox Code Playgroud)

这将解决您的"可能会改变为真或假以后"的问题,因为您可以在方法中添加/更改它,而不必更改代码中的任何其他内容.