java中判断一个字符是否为数字,可以通过Integer类的方法来判断,如果抛出异常,则不是数字,如下例子:
可以用异常来做校验/**
* 判断字符串是否是整数
*/
public static boolean isInteger(String value) {
try {
Integer.parseInt(value)//判断是否为数字
return true
} catch (NumberFormatException e) {//抛出异常
return false
}
}
java 检查是是不是数字:可以用异常来做校验
/**
* 判断字符串是否是整数
*/
public static boolean isInteger(String value) {
try {
Integer.parseInt(value)
return true
} catch (NumberFormatException e) {
return false
}
}
/**
* 判断字符串是否是浮点数
*/
public static boolean isDouble(String value) {
try {
Double.parseDouble(value)
if (value.contains("."))
return true
return false
} catch (NumberFormatException e) {
return false
}
}
/**
* 判断字符串是否是数字
*/
public static boolean isNumber(String value) {
return isInteger(value) || isDouble(value)
}
判断字符串是不是数字,大家可能会用一些java自带的方法,也有可能用其他怪异的招式,比如判断是不是整型数字,将字符串强制转换成整型,不是数字的就会抛出错误,那么就不是整型的了。但本文介绍的比较好的两种方法:1。java类库自带的方法:
public boolean isNum(String msg){
if(java.lang.Character.isDigit(msg.charAt(0))){
return true}return false}0202更新:发现以上方法写得不够到位,现在就改为下面的简单说明了,至于具体的方法实现字符串判断是否数字就不写了。
java.lang.Character.isDigit(char ch) boolean
isDigit 只能作用于char,所以判断字符串是否为数字,要一个一个拿出char进行判断。
2。用正则表达式
首先要import java.util.regex.Pattern 和 java.util.regex.Matcher
这两个包,接下来是代码
public boolean isNumeric(String str){Pattern pattern = Pattern.compile(”[0-9]*”)
Matcher isNum = pattern.matcher(str)
if( !isNum.matches() ){return false}return true}02
3。用正则表达式