51,410
社区成员
发帖
与我相关
我的任务
分享

public boolean isNumeric(String str){
for(int i=0;i<str.length();i++){
int chr=str.charAt(i);
if(chr<48 || chr>57) {
return false;
}
}
return true;
}
第二个是使用正则表达式.
public boolean isNumeric(String str){
Pattern pattern = Pattern.compile("[0-9]*");
return pattern.matcher(str).matches();
}
通过判断isNumeric方法的返回值来判断是否是输入了[0,9]的自然数.
boolean isNumeric = isNumeric(输入的字符串);
if(isNumeric){
是[0,9]的自然数.
}else{
不是[0,9]的自然数.
}