Java中怎样判断一个字符串是否是数字

Python011

Java中怎样判断一个字符串是否是数字,第1张

用java的异常机制,不仅可以判断是否是数字,还可以判断整数或者小数

public void checkInt(String bh){

try{

int num = Integer.parseInt(bh)//将输入的内容转换成int

System.out.println("是整数:"+num)//是整数

}catch (NumberFormatException e) {//转换成int类型时失败

try{

double d =Double.parseDouble(bh)//转成double类型

System.out.println("是小数:"+d)//是小数

}catch (NumberFormatException e2) {//转成double类型失败

System.out.println("不是数字")

}

}

}

//方法一:用JAVA自带的函数\x0d\x0apublic static boolean isNumeric(String str)\x0d\x0a{for (int i = str.length()--i>=0)\x0d\x0a{\x0d\x0aif (!Character.isDigit(str.charAt(i)))\x0d\x0a{\x0d\x0areturn false6 \x0d\x0a}\x0d\x0a}\x0d\x0areturn true\x0d\x0a}\x0d\x0a\x0d\x0a/*方法二:推荐,速度最快\x0d\x0a* 判断是否为整数 \x0d\x0a* @param str 传入的字符串 \x0d\x0a* @return 是整数返回true,否则返回false \x0d\x0a*/\x0d\x0apublic static boolean isInteger(String str) { \x0d\x0aPattern pattern = Pattern.compile("^[-\\+]?[\\d]*$") \x0d\x0areturn pattern.matcher(str).matches() \x0d\x0a}\x0d\x0a//方法三:public static boolean isNumeric(String str){\x0d\x0aPattern pattern = Pattern.compile("[0-9]*") return pattern.matcher(str).matches() \x0d\x0a}\x0d\x0a\x0d\x0a//方法四:public final static boolean isNumeric(String s) {if (s != null &&!"".equals(s.trim()))return s.matches("^[0-9]*$") else\x0d\x0areturn false\x0d\x0a}\x0d\x0a//方法五:用ascii码 public static boolean isNumeric(String str){for(int i=str.length()--i>=0){int chr=str.charAt(i) if(chr57)return false\x0d\x0a} return true\x0d\x0a}