Java中判斷字符串是否全是數字:
1.用 JAVA 自帶的 函數public static boolean isNumeric(String str){
for (int i = 0; i < str.length(); i++){
System.out.println(str.charAt(i));
if (!Character.isDigit(str.charAt(i))){
return false;
}
}
return true;
}
2.用 正則表達式
首先要import java .util.regex.Pattern 和 java .util.regex.Matcher
public boolean isNumeric(String str){
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(str);
if( !isNum.matches() ){
return false;
}
return true;
}
3.使用org.apache.commons.lang
org.apache.commons.lang.StringUtils;
boolean isNunicodeDigits=StringUtils.isNumeric("aaa123456789");
http://jakarta.apache.org/commons/lang/api-release/index.html 下面的解釋:
isNumeric
public static boolean isNumeric(String str)Checks if the String contains only unicode digits. A decimal point is not a unicode digit and returns false.
null will return false. An empty String ("") will return true.
StringUtils.isNumeric(null) = false
StringUtils.isNumeric("") = true
StringUtils.isNumeric(" ") = false
StringUtils.isNumeric("123") = true
StringUtils.isNumeric("12 3") = false
StringUtils.isNumeric("ab2c") = false
StringUtils.isNumeric("12-3") = false
StringUtils.isNumeric("12.3") = false
Parameters:
str - the String to check, may be null
Returns:
true if only contains digits, and is non-null
上面三種方式中,第二種方式比較靈活。
第一、三種方式只能校驗不含負號“-”的數字,即輸入一個負數-199,輸出結果將是false;
而第二方式則可以通過修改 正則表達式 實現校驗負數,將 正則表達式 修改為“^-?[0-9]+”即可,修改為“-?[0-9]+.?[0-9]+”即可匹配所有數字。
使用正則表達式:
|
1
2
3
4
5
6
7
8
|
public
boolean
isNumeric(String str) {
Pattern pattern = Pattern.compile(
"[0-9]*"
);
Matcher isNum = pattern.matcher(str);
if
(!isNum.matches()) {
return
false
;
}
return
true
;
}
|
但是這個方法並不安全,沒有對字符串進行空校驗。 在程序執行的時候很容易拋出異常。 例如執行:
|
1
2
3
4
5
6
|
public
static
void
main(String[] args) {
String str =
null
;
System.out.println(BarcodeChecksum.INSTANCE.isNumeric(str));
}
|
就會拋出異常:
|
1
2
3
4
5
6
7
|
Exception
in
thread
"main"
java.lang.NullPointerException
at java.util.regex.Matcher.getTextLength(Matcher.java:
1140
)
at java.util.regex.Matcher.reset(Matcher.java:
291
)
at java.util.regex.Matcher.<init>(Matcher.java:
211
)
at java.util.regex.Pattern.matcher(Pattern.java:
888
)
at com.ossez.bcu.util.BarcodeChecksum.isNumeric(BarcodeChecksum.java:
37
)
at com.ossez.bcu.util.BarcodeChecksum.main(BarcodeChecksum.java:
53
)
|
所以這個方法並不准確。 如果執行:
|
1
2
3
4
|
public
static
void
main(String[] args) {
String str =
""
;
System.out.println(BarcodeChecksum.INSTANCE.isNumeric(str));
}
|
將會返回 true。 這說明這個方法沒有對空字符串進行校驗。 可以使用 Apache 的 StringUtils.isNumeric() 函數進行判斷。 這個函數位於 org.apache.commons.lang.StringUtils; 中。 但是,需要注意,如果傳入參數為 "" 同樣也會你存在判斷不准確的情況,這時候需要首先對需要進行判斷的參數進行非空校驗,然后刪除傳入數據中的空格。
|
1
2
3
4
|
public
static
void
main(String[] args) {
String str =
""
;
System.out.println(StringUtils.isNumeric(str));
}
|
上面這個函數將會返回 true。 請先 trim 數據
