關于 String 的判空:
if (selection != null && !selection.equals("")) {
whereClause += selection;
}
//這是錯的
if (!selection.equals("") && selection != null) {
whereClause += selection;
}
注:“==”比較兩個變量本身的值,即兩個對象在內存中的首地址。而“equals()”比較字符串中所包含的內容是否相同。第二種寫法中,一旦 selection 真的為 null,則在執行 equals 方法的時候會直接報空指針異常導致不再繼續執行。
判斷字符串是否為數字:
// 調用java自帶的函數
public static boolean isNumeric(String number) {
for (int i = number.length(); --i >= 0;) {
if (!Character.isDigit(number.charAt(i))) {
return false;
}
}
return true;
}
// 使用正則表達式
public static boolean isNumeric(String number) {
Pattern pattern = Pattern.compile("[0-9]*");
return pattern.matcher(str).matches();
}
// 利用ASCII碼
public static boolean isNumeric(String number) {
for (int i = str.length(); --i >= 0;) {
int chr = str.charAt(i);
if (chr < 48 || chr > 57)
return false;
}
return true;
}