關(guān)于 String 的判空:
if (selection != null && !selection.equals("")) {
whereClause += selection;
}
//這是錯(cuò)的
if (!selection.equals("") && selection != null) {
whereClause += selection;
}
注:“==”比較兩個(gè)變量本身的值,即兩個(gè)對(duì)象在內(nèi)存中的首地址。而“equals()”比較字符串中所包含的內(nèi)容是否相同。第二種寫法中,一旦 selection 真的為 null,則在執(zhí)行 equals 方法的時(shí)候會(huì)直接報(bào)空指針異常導(dǎo)致不再繼續(xù)執(zhí)行。
判斷字符串是否為數(shù)字:
// 調(diào)用java自帶的函數(shù)
public static boolean isNumeric(String number) {
for (int i = number.length(); --i >= 0;) {
if (!Character.isDigit(number.charAt(i))) {
return false;
}
}
return true;
}
// 使用正則表達(dá)式
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;
}