java扫描仪多重验证

标签 java validation java.util.scanner

我想验证来自 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/

相关文章:

java - web.xml 在 Eclipse Juno 中未更新

validation - Flutter FormBuilder Dropdown 验证不起作用

validation - Laravel 验证器 - 违反完整性约束

java - 如何将每个数字打印到一定数量

java - 如何对自定义 Wicket 组件进行单元测试

java - Spring(Boot)对同一类的不同层进行验证注解

java - 类似于 Saiku 但不使用 Cube 的交互式报告工具

C# - 正则表达式验证日期和小时

java - 将文本文件作为标准输入

java - 如何让我的程序停止接受输入并运行该程序?