轉自:http://blog.sina.com.cn/s/blog_6e9c16890100na5q.html
1.使用類型轉換判斷
try {
String str="123abc";
int num=Integer.valueOf(str);//把字符串強制轉換爲數字
return true;//如果是數字,返回True
} catch (Exception e) {
return false;//如果拋出異常,返回False
}
2.使用正則表達式判斷
String str = "abc123";
boolean isNum = str.matches("[0-9]+");
//+表示1個或多個(如"3"或"225"),*表示0個或多個([0-9]*)(如""或"1"或"22"),?表示0個或1個([0-9]?)(如""或"7")
3.使用Pattern類和Matcher
String str = "123";
Pattern pattern = Pattern.compile("[0-9]+");
Matcher matcher = pattern.matcher((CharSequence) str);
boolean result = matcher.matches();
if (result) {
System.out.println("true");
} else {
System.out.println("false");
}
4.使用Character.isDigit(char)判斷
String str = "123abc";
if (!"".equals(str)) {
char num[] = str.toCharArray();//把字符串轉換爲字符數組
StringBuffer title = new StringBuffer();//使用StringBuffer類,把非數字放到title中
StringBuffer hire = new StringBuffer();//把數字放到hire中
for (int i = 0; i < num.length; i++) {
// 判斷輸入的數字是否爲數字還是字符
if (Character.isDigit(num[i])) {把字符串轉換爲字符,再調用Character.isDigit(char)方法判斷是否是數字,是返回True,否則False
hire.append(num[i]);// 如果輸入的是數字,把它賦給hire
} else {
title.append(num[i]);// 如果輸入的是字符,把它賦給title
}
}
}