[英]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.