本文實例總結了java判斷字符串是否為數字的方法。分享給大家供大家參考,具體如下:
方法一:用JAVA自帶的函數
1
2
3
4
5
6
7
8
|
public static boolean isNumeric(String str){ for ( int i = str.length();--i>= 0 ;){ if (!Character.isDigit(str.charAt(i))){ return false ; } } return true ; } |
方法二:用正則表達式
1
2
3
4
|
public static boolean isNumeric(String str){ Pattern pattern = Pattern.compile( "[0-9]*" ); return pattern.matcher(str).matches(); } |
方法三:用ascii碼
1
2
3
4
5
6
7
8
|
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 ; } |
希望本文所述對大家Java程序設計有所幫助。