我想验证来自 Scanner
的用户输入类。
验证它是一个整数并且它必须在[6000, 6999]
范围内
while(!in.hasNext("\\d+")) {
System.out.println("<Error: Enter numbers only!>");
System.out.println("Enter postal code :");
in.nextLine();
}
postalCode = in.nextInt();
in.nextLine();
如何添加验证以检查其是否在 [6000, 6999]
范围内?
已编辑 尝试了这个,这是输出。之后就停止了
输入邮政编码:
日
错误:仅输入数字!
输入邮政编码:
1
错误:邮政编码必须介于 6000-6999 之间!
输入邮政编码:
1000
System.out.println("Enter postal code :");
while(!in.hasNext("\\d+"))
{
System.out.println("<Error: Enter numbers only!>");
System.out.println("Enter postal code :");
in.nextLine();
}
postalCode = in.nextInt();
while(postalCode < 6000 || postalCode > 6999)
{
System.out.println("<Error: Postal code must be betwen 6000-6999 only!>");
System.out.println("Enter postal code :");
postalCode = in.nextInt();
while(!in.hasNext("\\d+"))
{
System.out.println("<Error: Enter numbers only!>");
System.out.println("Enter postal code :");
in.nextLine();
}
}
in.nextLine();
最佳答案
您需要一个新的 while 循环。说postalCode = in.nextInt();
,然后是一个新循环while(postalCode < 6000 || postalCode > 6999)
,最后提示用户输入新值。
postalCode = in.nextInt();
while(postalCode < 6000 || postalCode > 6999) {
System.out.println("Need a number between 6000 and 6999")
//... revalidate that it is an integer
postalCode = in.nextInt();
}
关于java扫描仪多重验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37619510/