【问题标题】:How to validate user's input, and read-in their input again if it invalidates, using try-catch?如何验证用户的输入,如果输入无效,如何使用 try-catch 再次读取他们的输入?
【发布时间】:2016-03-05 02:17:31
【问题描述】:

我想使用异常处理机制来验证用户输入。

例如,假设我要求用户输入整数输入并且他们输入一个字符。在这种情况下,我想告诉他们他们输入了错误的输入,除此之外,我希望他们提示他们再次读取整数,并继续这样做直到他们输入一个可接受的输入。

我见过一些类似的问题,但是他们并没有再次接受用户的输入,他们只是打印出输入不正确。

使用 do-while,我会做这样的事情:

Scanner reader = new Scanner(System.in);  
System.out.println("Please enter an integer: ");
int i = 0;
do {
  i = reader.nextInt();
} while (  ((Object) i).getClass().getName() != Integer  ) {
  System.out.println("You did not enter an int. Please enter an integer: ");
}
System.out.println("Input of type int: " + i);

问题:

  1. 在检查while 条件的语句到达之前,将在第5 行引发InputMismatchException

  2. 我确实想学习使用异常处理习语进行输入验证。

所以当用户输入错误的输入时,我如何 (1) 告诉他们他们的输入不正确并 (2) 再次读取他们的输入(并继续这样做,直到他们输入正确的输入),使用 try-catch 机制?


编辑:@Italhouarne

import java.util.InputMismatchException;
import java.util.Scanner;


public class WhyThisInfiniteLoop {

    public static void main (String [] args) {
        Scanner reader = new Scanner(System.in); 
        int i = 0; 
        System.out.println("Please enter an integer: ");

        while(true){
          try{
             i = reader.nextInt();
             break;  
          }catch(InputMismatchException ex){
             System.out.println("You did not enter an int. Please enter an integer:");
          }
        }

        System.out.println("Input of type int: " + i);
    }

}

【问题讨论】:

    标签: java validation input exception-handling


    【解决方案1】:

    在 Java 中,最好仅在“异常”情况下使用 try/catch。我会使用Scanner 类来检测是否输入了int 或其他一些无效字符。

    import java.util.Scanner;
    
    public class Test {
    
        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            boolean gotInt = false;
    
            while (!gotInt) {
                System.out.print("Enter int: ");
                if (scan.hasNextInt()){
                    gotInt = true;
                }
                else {
                    scan.next(); //clear current input
                    System.out.println("Not an integer");
                }
            }
            int theInt = scan.nextInt();
        }
    } 
    

    【讨论】:

      【解决方案2】:

      给你:

      Scanner sc = new Scanner(System.in);
      boolean validInput = false;
      int value;
      do{
          System.out.println("Please enter an integer");
          try{
              value = Integer.parseInt(sc.nextLine());
              validInput = true;
          }catch(IllegalArgumentException e){
              System.out.println("Invalid value");
          }
      }while(!validInput);
      

      【讨论】:

        【解决方案3】:

        您可以尝试以下方法:

        Scanner reader = new Scanner(System.in);  
        System.out.println("Please enter an integer: ");
        int i = 0;
        
        while(true){
          try{
             i = reader.nextInt();
             break;  
          }catch(InputMismatchException ex){
             System.out.println("You did not enter an int. Please enter an integer:");
          }
        }
        
        System.out.println("Input of type int: " + i);
        

        【讨论】:

        • 但是while(true) 是一个无限循环
        • @Solace 不,因为break 会在没有抛出异常时退出它(意味着输入是一个 int)。
        • 我测试了你的代码,它确实进入了一个无限循环,虽然不是我(错误地)预期的地方,而是在 catch 块中。它一直在打印You did not enter an int. Please enter an integer:。请参阅有问题的编辑。虽然为什么会发生这种情况我无法理解。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多