如何验证尼姆应该包含10位数字



我已经确定输入的必须是int并且必须是正数,现在我想添加验证,以便输入的数字必须包含10位

try {
nim = Integer.parseInt(txtNIM.getText());
} catch (NumberFormatException e) {
throw new numberException();
}if (nim < 0) {
throw new PositiveException();
}
try {
nimStr=txtNIM.getText();
if(nimStr.length() !=10){
throw new numberLengthNotTenException(); //this is a custom exception that  
//needs to be created outside by 
//yourself
// or else you can just print something to console directly and not throw an error
}
else{
nim = Integer.parseInt(nimStr);
}


} 
catch (NumberFormatException e) {
throw new numberException();
}
catch(numberLengthNotTenException e){ //add this if you want to throw custom exception
System.out.println(e);
}
if (nim < 0) {
throw new PositiveException();
}

如何创建自定义异常

使用带有正则表达式(RegEx(的String#matches((方法,但是,您应该记住,10位数字可能超过21474833647的整数MAX_VALUE,并且将抛出异常,因此,Integer变量应该是Long Integer数据类型,并且使用Long.parseLong():解析数字字符串

String nimStrg = txtNIM.getText();
long nim;
/* The string numerical value must be no more
and no less than ten digits and can not 
start with zero (0).                */
if (!nimStrg.matches("^[1-9][0-9]{9}$")) {
System.out.println("Invalid Numerical Value!");
// exit mechanism here if it's required...
}
else {
nim = Long.parseLong(nimStrg);
}
try {
int count = 0;
nim = Integer.parseInt(txtNIM.getText());
} catch (NumberFormatException e) {
throw new numberException();
}if (nim < 0) {
throw new PositiveException();
}
int nim1 = nim;
for (nim1 != 0; nim1 /= 10, ++count) {
}
if (count < 10) {
throw new PositiveException();
}

count变量将计算数字的总位数

最新更新