2014-03-19 18 views
1

單個元素的字符串數組爲布爾

String test = "[true]" 

我如何檢查是否這可能是一個布爾元素?有沒有一個乾淨的方式來做到這一點,或者我需要創建一個功能來修剪兩側,並檢查類型?

+1

'test.toLowerCase()。contains(「true」)|| test.toLowerCase()。contains(「false」)'? –

+0

多數民衆贊成它,謝謝! – Badmiral

+2

'test =='[true]''? –

回答

3

您可以編寫自己的功能括號中是

public boolean convertToBoolean(String input) throws Exception{ 
    if(input == null){ 
     throw new Exception("Input is null"); 
    } 
    if(input.toLowerCase().contains("true")){ 
     return true; 
    } 
    else { 
     return false; 
    } 
} 
+0

謝謝!正是我在找的東西。不會想到檢查空值 – Badmiral

1

修剪,然後使用Boolean(String s)構造函數來創造一個新的布爾

String sb = "[true]"; 
Boolean b = new Boolean(sb.substring(1, sb.length()-1)); 

現在你可以在你的,如果使用這個布爾聲明:

if(b) 
     System.out.println(true); 
    else 
     System.out.println(false); 
相關問題