我正在编写文件阅读器,其目的是让用户输入一个代表文本文件中行号的数字。保存此数字的变量的类型为int
。但是,当用户输入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
}
}
我的问题是,有哪些可能的技术可以进行验证? 谢谢。
答案 0 :(得分: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
}
}
答案 1 :(得分: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
}
答案 2 :(得分: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