如何将字符串对象转换为布尔对象?


当前回答

您可以直接设置布尔值等价于任何字符串的系统类 并访问它的任何地方..

System.setProperty("n","false");
System.setProperty("y","true");

System.setProperty("yes","true");     
System.setProperty("no","false");

System.out.println(Boolean.getBoolean("n"));   //false
System.out.println(Boolean.getBoolean("y"));   //true   
 System.out.println(Boolean.getBoolean("no"));  //false
System.out.println(Boolean.getBoolean("yes"));  //true

其他回答

您可以直接设置布尔值等价于任何字符串的系统类 并访问它的任何地方..

System.setProperty("n","false");
System.setProperty("y","true");

System.setProperty("yes","true");     
System.setProperty("no","false");

System.out.println(Boolean.getBoolean("n"));   //false
System.out.println(Boolean.getBoolean("y"));   //true   
 System.out.println(Boolean.getBoolean("no"));  //false
System.out.println(Boolean.getBoolean("yes"));  //true

我是这样做的:

“1 # #真”。Contains(字符串)

因为我的情况大多是1或真。我使用散列作为分隔符。

public static boolean stringToBool(String s) {
        s = s.toLowerCase();
        Set<String> trueSet = new HashSet<String>(Arrays.asList("1", "true", "yes"));
        Set<String> falseSet = new HashSet<String>(Arrays.asList("0", "false", "no"));

        if (trueSet.contains(s))
            return true;
        if (falseSet.contains(s))
            return false;

        throw new IllegalArgumentException(s + " is not a boolean.");
    }

我把字符串转换成布尔值的方法。

要获得String的布尔值,请尝试以下方法:

public boolean toBoolean(String s) {
    try {
        return Boolean.parseBoolean(s); // Successfully converted String to boolean
    } catch(Exception e) {
        return null; // There was some error, so return null.
    }
}

如果有错误,它将返回null。 例子:

toBoolean("true"); // Returns true
toBoolean("tr.u;e"); // Returns null

访问http://msdn.microsoft.com/en-us/library/system.boolean.parse.aspx

这会让你知道该怎么做。

这是我从Java文档中得到的:

方法的细节 parseBoolean parseBoolean(String s) 将字符串参数解析为布尔值。如果字符串参数不为空,返回的布尔值表示true,并且忽略大小写,等于字符串"true"。 参数: s -包含要解析的布尔表示的字符串 返回:由字符串参数表示的布尔值 自: 1.5