java中怎么判断数字

Python020

java中怎么判断数字,第1张

java中判断一个字符是否为数字,可以通过Integer类的方法来判断,如果抛出异常,则不是数字,如下例子:

可以用异常来做校验

/**

  * 判断字符串是否是整数

  */

 public static boolean isInteger(String value) {

  try {

   Integer.parseInt(value)//判断是否为数字

   return true

  } catch (NumberFormatException e) {//抛出异常

   return false

  }

 }

//方法一:用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}

用正则表达式

public static boolean isNumericzidai(String str) {

Pattern pattern = Pattern.compile("-?[0-9]+.?[0-9]+")

Matcher isNum = pattern.matcher(str)       if (!isNum.matches()) {            return false

}        return true

}12345678

网上给出的最好的方法,可惜还是错误;首先正则表达式-?[0-9]+.?[0-9]+这里就错误 

网上说:可匹配所有数字。 

比如:

double aa = -19162431.1254

String a = "-19162431.1254"

String b = "-19162431a1254"

String c = "中文"

System.out.println(isNumericzidai(Double.toString(aa)))

System.out.println(isNumericzidai(a))

System.out.println(isNumericzidai(b))

System.out.println(isNumericzidai(c))12345678

结果

falsetruetruefalse1234

正确的正则表达式是:-?[0-9]+\\.?[0-9]*,点号.,是匹配任意字符,需要进行转义。