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中判断一个字符是否为数字,可以通过Integer类的方法来判断,如果抛出异常,则不是数字,如下例子:
可以用异常来做校验/**
* 判断字符串是否是整数
*/
public static boolean isInteger(String value) {
try {
Integer.parseInt(value)//判断是否为数字
return true
} catch (NumberFormatException e) {//抛出异常
return false
}
}
1.使用Character.isDigit(char)判断char num[] = str.toCharArray()//把字符串转换为字符数组
StringBuffer title = new StringBuffer()//使用StringBuffer类,把非数字放到title中
StringBuffer hire = new StringBuffer()//把数字放到hire中
for (int i = 0i <num.lengthi++) {
// 判断输入的数字是否为数字还是字符
if (Character.isDigit(num[i])) {把字符串转换为字符,再调用Character.isDigit(char)方法判断是否是数字,是返回True,否则False
hire.append(num[i])// 如果输入的是数字,把它赋给hire} else {title.append(num[i])// 如果输入的是字符,把它赋给title}}}
2.使用类型转换判断try {String str="123abc"
int num=Integer.valueOf(str)//把字符串强制转换为数字
return true//如果是数字,返回True
} catch (Exception e) {
return false//如果抛出异常,返回False}
3.使用正则表达式判断
String str = ""
boolean isNum = str.matches("[0-9]+")
//+表示1个或多个(如"3"或"225"),*表示0个或多个([0-9]*)(如""或"1"或"22"),?表示0个或1个([0-9]?)(如""或"7")
ps:这个方法只能用于判断是否是正整数