【问题标题】:More efficient way to handle user input data validation?处理用户输入数据验证的更有效方法?
【发布时间】:2022-01-23 22:01:29
【问题描述】:

在 Java 中,我有两个 while 循环来验证用户输入并在用户输入错误数据类型时不断提示用户。在这个程序中,我只有 2 个问题,但我可以想象这样一个场景,我有超过 10 个问题,此时 10 个 while 循环将是阅读和维护繁琐的代码。在继续提示用户的同时,有没有更有效的方法来检查错误?我最初的想法是将while循环和错误检查打包到一个单独的类函数中,并在请求输入时调用它。

import java.util.*; 

公共类增加年龄{

public static void main(String args[]){
    Scanner userInput = new Scanner(System.in);
    boolean validInput = true;
    String coolName = "Adam";
    int coolAge = 0;

    while(validInput){
        try{
            System.out.print("Hello, what is your first name? ");
            coolName = userInput.nextLine();
            validInput = false;
        }
        catch(Exception error){
            System.out.println("Invalid input, try again!");
            userInput.next();
        }
    }
    validInput = true;
    while(validInput){
        try{
            System.out.print("Hi "+ coolName + "! How old are you?");
            coolAge = userInput.nextInt();
            validInput = false;
        }
        catch(Exception error){
            System.out.println("Invalid input, try again!");
            userInput.next();
        }
    }
    System.out.println("Hello "+ coolName + ", in ten years you will be " + (coolAge+10));
    userInput.close();


}

}

【问题讨论】:

  • 顺便说一句,有时您应该检查输入验证是在 HTML 5 中完成的。输入上的“类型”属性将输入限制为您正在查找的数据类型,以及其他属性,例如“模式”和“最小值/最大值”(用于数字输入)提供了一个内置框架(Java 缺乏)来处理用户输入。
  • 您对“有效”一词的使用很奇怪。当输入 not 有效时,您已将其编码为 validInput 为 true。

标签: java function user-input


【解决方案1】:

只需实现private int getIntegerInput(String prompt)private String getStringInput(String prompt),每个都或多或少与您已经编码的两个循环相同。

这是避免代码重复的常用方法 - 实现“帮助”例程以用于编写您的预期功能。

即使您不必担心重复,它也是一种有用的代码分区,使其更易于理解 - 例如,“获取输入”代码明显不同于“处理输入”代码。


例子:

private String getStringInput(Scanner scanner, String prompt) {
    String input = null;
    boolean validInput = false;
    while (!validInput) {
       try {
            System.out.print(prompt);
            input = scanner.nextLine();
            validInput = !input.isEmpty();
        }
        catch (Exception error) {
            System.out.println("Invalid input, try again!");
        }
    }
    return input;
}

请注意,我修复了“validInput”的使用以使其有意义,并且我假设您想在空输入行上重新提示。

用法就是这样

String coolName = getStringInput(userInput, "What is your first name? ");

【讨论】:

    猜你喜欢
    • 2012-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多