JAVA中怎么判断是否数字类型?
__________________________________________不明白1 判断obj是不是java.lang.Number的实例if (obj instanceof Number) {
}2 判断一个字符串str是不是数字
方法1
static final String number = "123456789.";
for (int i = 0; i < str.length; i++) {
if (number.indexOf(str.charAt(i)) == -1) {
return false;
}
}
return true; 方法2
不建议使用
try {
Long.parseLong(str)
} catch (NumberFormatException nfe) {
return false;
}
return true;
__________________________________________不明白1 判断obj是不是java.lang.Number的实例if (obj instanceof Number) {
}2 判断一个字符串str是不是数字
方法1
static final String number = "123456789.";
for (int i = 0; i < str.length; i++) {
if (number.indexOf(str.charAt(i)) == -1) {
return false;
}
}
return true; 方法2
不建议使用
try {
Long.parseLong(str)
} catch (NumberFormatException nfe) {
return false;
}
return true;
您提到的方法2为什么不提倡使用?难道会造成判断不准确么?
throws NumberFormatException
{
if (s == null) {
throw new NumberFormatException("null");
} if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " + radix +
" greater than Character.MAX_RADIX");
} long result = 0;
boolean negative = false;
int i = 0, max = s.length();
long limit;
long multmin;
int digit; if (max > 0) {
if (s.charAt(0) == '-') {
negative = true;
limit = Long.MIN_VALUE;
i++;
} else {
limit = -Long.MAX_VALUE;
}
multmin = limit / radix;
if (i < max) {
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw new NumberFormatException(s);
} else {
result = -digit;
}
}
while (i < max) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw new NumberFormatException(s);
}
if (result < multmin) {
throw new NumberFormatException(s);
}
result *= radix;
if (result < limit + digit) {
throw new NumberFormatException(s);
}
result -= digit;
}
} else {
throw new NumberFormatException(s);
}
if (negative) {
if (i > 1) {
return result;
} else { /* Only got "-" */
throw new NumberFormatException(s);
}
} else {
return -result;
}
}他也是一个字符一个字符的判断,如果有一个不是数字就抛出NumberFormatException,其实这个工作你自己就可以做,为什么还要让它出现一次Exception呢我之所以说不提倡,是出于对效率的考虑。