Java中如何判断一个字符串是否为数字

方法一:异常处理

    public static boolean isInteger(String str){
        
        try {
            Integer i = Integer.parseInt(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

方法二:正则匹配

boolean isNum = str.matches("[0-9]+"); 

方法三:ascii码判断

public static boolean isInteger(String str){
    for(int i=str.length();--i>=0;){
        int chr=str.charAt(i);
        if(chr<48 || chr>57)
            return false;
    }
   return true;
}     

方法四:逐个字符进行判断

public static boolean isInteger(String str) {
        for (int i = str.length(); --i >= 0;) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

 

posted @ 2018-11-01 16:25  做个读书人  阅读(1207)  评论(0编辑  收藏  举报