4

我正在编写一个文件阅读器,其想法是让用户输入一个数字,该数字代表文本文件中的行号。保存这个数字的变量是类型int。但是,当用户输入 a 时String,Java 会抛出InputMismatchException异常,我想要的是在catch子句中有一个循环,我将在其中循环,直到用户输入一个有效值,即一个int. 骨架看起来像这样:

 public void _____ throws IOException {
    try {
    // Prompting user for line number
    // Getting number from keyboard
    // Do something with number
    } catch (InputMismatchException e) {
       // I want to loop until the user enters a valid input
       // When the above step is achieved, I am invoking another method here
    }  
}

我的问题是,有哪些可能的技术可以进行验证?谢谢你。

4

3 回答 3

4
while(true){ 
   try { 
        // Prompting user for line number 
        // Getting number from keyboard 
        // Do something with number 
        //break; 
       } catch (InputMismatchException e) { 
            // I want to loop until the user enters a valid input 
            // When the above step is achieved, I am invoking another method here 
       } 
   } 
于 2012-05-03T04:13:55.993 回答
3

避免使用异常进行流量控制。捕获异常,但只打印一条消息。此外,确实需要循环内的循环。

就这么简单:

public void _____ throws IOException {
    int number = -1;
    while (number == -1) {
        try {
            // Prompt user for line number
            // Getting number from keyboard, which could throw an exception
            number = <get from input>;
        } catch (InputMismatchException e) {
             System.out.println("That is not a number!");
        }  
    }
    // Do something with number
}
于 2012-05-03T04:54:18.873 回答
2

你可以避免Exception

Scanner sc = new Scanner(System.in);
while(sc.hasNextLine())
    String input = sc.nextLine();
    if (isNumeric(input) {
        // do something
        // with the number
        break; // break the loop
    }
}

方法isNumeric

public static boolean isNumeric(String str) {
    return str.matches("^[0-9]+$");
}

如果要使用对话框输入数字:

String input = JOptionPane.showInputDialog("Input a number:"); // show input dialog
于 2012-05-03T04:58:40.293 回答