Можно ли и как заново выполнить try при exception?
private static Scanner scan = new Scanner(System.in);
public static int input() {
System.out.print("Please enter an integer: ");
try {
return scan.nextInt();
} catch (InputMismatchException e) {
return input();
}
}
Пытаюсь вводить данные с помощью рекурсии.
Как только происходит InputMismatchException:
1. Заново вызивается input()
2. Выполняется try
3. Не ожидая ввода, сразу же выполняется catch*
4. И так бесконечно.
*Даже если при дебагинге получается передавать правилое значение
Ответы (2 шт):
Автор решения: Alexander Chernin
→ Ссылка
Лучше воспользоваться вечным циклом:
private static Scanner scan = new Scanner(System.in);
public static int input() {
String message = "Please enter an integer: ";
while(true) {
System.out.print(message);
try {
return scan.nextInt();
} catch (InputMismatchException e) {
scan.nextLine(); // или next()
message = "Please, try again to enter an integer: ";
}
}
}
Ваш вариант тоже заработает как надо, если вызывать nextLine(), или next():
private static Scanner scan = new Scanner(System.in);
public static int input() {
System.out.print("Please enter an integer: ");
try {
return scan.nextInt();
} catch (InputMismatchException e) {
scan.nextLine();
return input();
}
}
Автор решения: Timur Irdyneev
→ Ссылка
public static int input() {
System.out.print("Please enter an integer: ");
try {
return scan.nextInt();
} finally {
return input();
}
}