Java 用户输入错误处理

Java User Input Error Handling

我有一个简单的 java 程序,它接受整数、双精度和字符串类型的 3 个用户输入。我想知道 best/most 对所有这些输入执行错误处理的有效方法,以保持程序 运行,通知用户他们输入了错误的输入并再次询问他们这个问题。任何帮助将不胜感激。

这是我的代码

    Scanner scan = new Scanner(System.in);
    int inputInt;
    double inputDbl;
    String inputString;


    System.out.print("Please enter a whole number: ");
    inputInt = scan.nextInt();      
    System.out.print("Please enter a decimal number: ");
    inputDbl = scan.nextDouble();
    System.out.print("Please enter a string: ");
    inputString = scan.next().toLowerCase();    
boolean validated = false;

// this keeps user locked until he/she provides valid inputs for all variables
while(!validated) {
  //get inputs here
  // ..

  // lastly
  validated = validateLogic(inInt, inDbl, inStr);
}

// keep going

如果你想对每个输入单独验证,你应该写while循环3次。

将其拆分为 n 方法,其中 n 是有多少用户输入。

为每个用户输入创建一个获取输入的方法:

String getStringInput(){
    System.out.println("Enter input");
    String input = scan.next();

    //check the input to make sure it is correct
    if(input.equals("foo")){
        //if the input is incorrect tell the user and get the new input
        System.out.println("Invalid Input");
        //simply return this method if the input is incorrect.
        return getStringInput();
    }

    //return the input if it is correct
    return input;
}

对于获取输入的主要方法,只需调用方法:

void getAll(){
    String stringValue = getStringInput();
}

现在可以轻松获取任意数量的输入并检查输入是否正确。

感谢所有输入的人,你们真棒。我选择只使用一个使用布尔触发器的简单 dowhile 循环。我之前尝试过使用 try catch,但最终编写了大量代码来执行非常基本的输入检查。所以这里不要有任何异常处理,我希望这样就没有必要了。希望它不会让我失望

do {
        System.out.print("Please enter a whole number: ");
        if (scan.hasNextInt()){     
        inputInt = scan.nextInt();
        validInput = true;
        } else
            System.out.println("You have entered incorrect input! Please enter a whole number only");
            scan.nextLine();
        } while (validInput == false);  

        validInput = false;

        do {
        System.out.print("Please enter a decimal number: ");
        ......
        ......