摘自:https://blog.csdn.net/qq_42133100/article/details/92158507
方法一:用JAVA自帶的函數(只能判斷正整數 )
2 public static boolean isNumeric(String str){
3 for (int i = str.length();--i>=0;){
4 if (!Character.isDigit(str.charAt(i))){
5 return false;
6 }
7 }
8 return true;
9 }
方法二:正則(推薦,速度最快)
public static boolean isInteger(String str) {
Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
return pattern.matcher(str).matches();
}
方法三:正則
public static boolean isNumeric(String str){
Pattern pattern = Pattern.compile("[0-9]*");
return pattern.matcher(str).matches();
}
方法四:正則
public final static boolean isNumeric(String s) {
if (s != null && !"".equals(s.trim()))
return s.matches("^[0-9]*$");
else
return false;
}
方法五:用ascii碼
public static boolean isNumeric(String str){
for(int i=str.length();--i>=0;){
int chr=str.charAt(i);
if(chr<48 || chr>57)
return false;
}
return true;
}
方法六:采用強制類轉換來判斷一個字符串是否為數字 (有局限性,如果要判斷是int型或double型,就必須要調整轉換語句,但可以判斷正負)
try {
//Integer num = Integer.valueOf(str);
Double num2 = Double.valueOf(str);
//System.out.println("Is Number!" + num);
System.out.println("Is Number!" + num2);
} catch (Exception e) {
System.out.println("Is not Number!");
}
方法七:采用正則表達式的方式來判斷一個字符串是否為數字,這種方式判斷面比較全面,可以判斷正負、整數小數 (推薦)
//?:0或1個, *:0或多個, +:1或多個
Boolean strResult = str.matches("-?[0-9]+.?[0-9]*");
if(strResult == true) {
System.out.println("Is Number!");
} else {
System.out.println("Is not Number!");
}
