在下面显示的Java代码中,我接受用户输入的两个double值,并将这些值包装在处理InputMismatchException的try-catch中。 我还围绕try-catch块包装了一个do-while循环。 我试图以一种方式来处理这样的情况:如果用户为“number2”输入了错误的类型,那么循环就不会重新开始并要求用户重新输入“number1”。 我一直在为实现这一点的最佳方法而挠头,并对任何反馈或建议持开放态度。
所以测试用例应该是; 用户为number1输入了正确的类型,但为number2输入了错误的类型,在这种情况下,我如何实现代码,使它只要求重新输入number2,而不是重新启动整个循环。 我试过嵌套的try-catch,嵌套的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);
}
}
您可以提取取供应商的方法
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()
)
只需将读取这两个值的过程分开。 通过这种方式,您可以单独检查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);
试试这个,
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);