我想验证来自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]
范围内?
EDITED 尝试了这个,这是输出。在此之后停止
输入邮政编码:
d
错误:仅输入数字!
输入邮政编码:
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();
答案 0 :(得分:2)
你需要一个新的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();
}