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.   

    用catch NumberException来判断
      

  2.   

    请问binny:
       您提到的方法2为什么不提倡使用?难道会造成判断不准确么?
      

  3.   

    首先,你要知道,NumberException是用来处理异常的,最好不要用来控制流程的。而且,虽然捕捉一次异常很容易,但是创建一次异常会消耗很多的系统资源,因为他要给整个结构作一个快照另外,你看一下JDK源码,就知道    public static long parseLong(String s, int radix)
                  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呢我之所以说不提倡,是出于对效率的考虑。