java - 在 do-while 循环中的 Java try-catch
问题描述
在下面显示的 Java 代码中,我接受两个双精度的用户输入,并将这些值包装在处理 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()
)
推荐阅读
- excel - Excel Power 数据透视表中的额外列
- arrays - 如何检查值是否存在于数组中?
- amazon-web-services - 为什么 AWS X-Ray 不显示错误?
- ruby-on-rails - 如何解决您的 Ruby 版本是 2.3.1,但您的 Gemfile 指定的是 2.5.1?
- mongodb - 本地 MongoDb 与 CosmosDb 查询执行的差异
- php -
- ios - iOS swift web 视图打开相机
- javascript - 为什么html密码字段变空
- python - Windows 10 到 Windows 8.1 的 Pyinstaller 问题
- javascript - 带有音频的 RTCMulticonnection 屏幕共享不起作用