在下面显示的Java代码中,我接受两个双精度的用户输入,并将这些值包装在一个处理InputMismatchException的try-catch中。我还在这个try-catch块周围包装了一个do-while循环。我正在尝试以一种可以处理以下情况的方式来编写代码:如果用户为“ number2”输入了错误的类型,则循环不会重新开始,并要求用户再次输入“ number1”。我一直在努力寻求实现此目标的最佳方法,并且愿意接受任何反馈或建议。
因此,测试用例将是;用户为number1输入正确的类型,但为number2输入错误的类型,在这种情况下,我如何实现代码,以便它仅要求重新输入number2而不是重新启动整个循环。我已经尝试过嵌套尝试捕获,嵌套do-whiles等。有什么想法吗?
import java.util.InputMismatchException;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean continueInput = true;
do {
try {
System.out.print("Enter your first number: ");
double number1 = input.nextDouble();
System.out.print("Enter your second number: ");
double number2 = input.nextDouble();
System.out.println("You've entered the numbers " + number1 + " " + number2);
continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again, a double is required.");
input.nextLine();
}
} while (continueInput);
}
}
答案 0 :(得分:1)
您可以提取采用供应商的方法
private <T> T executeWithRetry(String initialText, String retryText, Supplier<T> supplier) {
System.out.println(initialText);
while (true) {
try {
return supplier.get();
} catch (InputMismatchException ex) {
System.out.println(retryText);
}
};
}
并像使用它
double number1 = executeWithRetry(
"Enter your first number: ",
"Try again, a double is required.",
() -> input.nextDouble()
)
答案 1 :(得分:1)
只需将读取两个值的过程分开即可。这样,您可以单独检查是否发生InputMismatchException并为每个变量单独处理。
continueInput = false;
do {
try {
System.out.print("Enter your first number: ");
double number1 = input.nextDouble();
} catch (InputMismatchException ex) {
System.out.println("Try again, a double is required.");
continueInput = true;
}
} while (continueInput);
continueInput = false;
do {
try {
System.out.print("Enter your second number: ");
double number2 = input.nextDouble();
} catch (InputMismatchException ex) {
System.out.println("Try again, a double is required.");
continueInput = true;
}
} while (continueInput);
答案 2 :(得分:1)
尝试一下
Scanner input = new Scanner(System.in);
boolean continueInput = true;
double number1 = 0;
while (continueInput) {
try {
System.out.print("Enter your first number: ");
number1 = input.nextDouble();
continueInput = false;
} catch (InputMismatchException ex) {
System.out.println("Try again, a double is required.");
input.nextLine();
}
}
continueInput = true;
double number2 = 0;
while (continueInput) {
try {
System.out.print("Enter your second number: ");
number2 = input.nextDouble();
continueInput = false;
} catch (InputMismatchException ex) {
System.out.println("Try again, a double is required.");
input.nextLine();
}
}
System.out.println("You've entered the numbers " + number1 + " " + number2);