參考自 這裡
- 用JAVA自帶的函數
- 用正則表達式
執行結果 :
- 用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 ;
- }
- package test.stlib;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- public class JudgeStrAsNum {
- public static void main(String[] args) {
- String intStrArry[] = {"1.0", "-1.2", "0.3", "123.0", "abc", "a123", ".12"};
- Pattern ptn = Pattern.compile("^-?[0-9]+(\\.[0-9]+)?$");
- Matcher mth = null;
- for(String intStr:intStrArry)
- {
- mth = ptn.matcher(intStr);
- if(mth.find())
- {
- System.out.printf("\t[Info] %s is a number.\n", intStr);
- }
- else
- {
- System.out.printf("\t[Info] %s is not a number.\n", intStr);
- }
- }
- }
- }
This message was edited 3 times. Last update was at 16/08/2012 10:10:45
作者已經移除這則留言。
回覆刪除感謝你的回覆, 的確會有正負數與小數點的問題. 我有修改一下 Regex, 雖然解決了小數點與正負數, 但應該還是不夠嚴謹.
回覆刪除