[英]Java - looping in try-catch block
我正在编写文件阅读器,其目的是让用户输入一个代表文本文件中行号的数字。 保存此数字的变量的类型为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
}
}
我的问题是,有哪些可能的技术可以进行验证? 谢谢。
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
}
}
避免使用流量控制的例外。 捕获异常,但只打印消息。 此外,需要循环内的循环。
这很简单:
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
}
你可以避免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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.