1. 自己写了个方法
public static boolean isNumber(String str) {
char[] ch = str.toCharArray();
int dash=0;
for(int i=0;i<ch.length;i++) {
//判断是不是负数,第一位是不是负号
if(ch[i]=='-'&&i==0) {
continue;
}
//判断有没有没小数点,小数点只能有一位
if(ch[i]=='.') {
dash++;
if(dash==1) {
continue;
}
return false;
}
//判断是不是数字0-9
if(ch[i]<48||ch[i]>57) {
return false;
}
}
return true;
}
使用正则类Pattern
public static boolean patternNumber(String str) {
Pattern p = Pattern.compile("[-]??\\d+\\.??\\d*?");
return p.matcher(str).matches();
}