java - 如何从用户输入错误的地方重复输入?
问题描述
我有一些二传手。问题是,我想从用户准确输入错误的地方启动程序。例如:如果用户提出错误的输入,street
它不会name
再次从 . 开始,而是从street
. 我知道这个选项,但实施起来很糟糕。
boolean isBadInput = true;
while (isBadInput) {
try {
System.out.print("name: ");
client.setName(input.next());
isBadInput = false;
} catch (InputMismatchException e) {
System.out.println("bad input, try again");
}
}
isBadInput = true;
while (isBadInput) {
try {
System.out.print("surname: ");
client.setSurname(input.next());
isBadInput = false;
} catch (InputMismatchException e) {
System.out.println("bad input, try again");
}
}
isBadInput = true;
// and so on
System.out.print("city: ");
client.setCity(input.next());
System.out.print("rent date: ");
client.setRentDate(input.next());
System.out.print("street: ");
client.setStreet(input.next());
System.out.print("pesel number: ");
client.setPeselNumber(input.nextLong());
System.out.print("house number: ");
client.setHouseNumber(input.nextInt());
正如你所看到的,我需要编写很多 try/catch 块来完成它。还有其他选择吗?我不想做这样的事情:
boolean isBadInput = true;
while (isBadInput) {
try {
System.out.print("name: ");
client.setName(input.next());
System.out.print("surname: ");
client.setSurname(input.next());
System.out.print("city: ");
client.setCity(input.next());
System.out.print("rent date: ");
client.setRentDate(input.next());
System.out.print("street: ");
client.setStreet(input.next());
System.out.print("pesel number: ");
client.setPeselNumber(input.nextLong());
System.out.print("house number: ");
client.setHouseNumber(input.nextInt());
} catch (InputMismatchException e) {
System.out.println("bad input, try again");
}
}
因为程序会从name
每次开始重复。
解决方案
您可以在方法中移动处理 while/try/catch :
public String takeInput(Scanner input, String label) {
while (true) {
try {
System.out.print(label + ": ");
return input.next();
} catch (InputMismatchException e) {
System.out.println("bad input, try again");
input.next();
}
}
}
你可以这样做:
client.setname(takeInput(input, "name"));
client.setSurname(takeInput(input, "surname"));
对于采用 String 以外的其他内容的输入,您可以引入另一种方法或概括实际的 takeInput() 方法。
例如,您可以通过这种方式对其进行概括:
public <T> T takeInput(Callable<T> input, String label) {
while (true) {
try {
System.out.print(label + ": ");
return input.call();
} catch (InputMismatchException e) {
System.out.println("bad input, try again");
input.next();
}
catch (Exception e) {
System.out.println("other exception...");
}
}
}
并使用它:
Scanner input = ...;
String name = takeInput(input::next, "name");
long peselNumber = takeInput(input::nextLong, "pesel number");
推荐阅读
- c# - 如何跨多个方法传递 Dapper TransactionScope
- sql-server - NHibernate Linq OrderBy+Select+Distinct 产生无效的 SQL
- java - 带有 Jetty 的 CDI 不工作(不注入 bean)
- javascript - 使用动态样式和模板渲染角度组件
- laravel - 使用 whereIn 仅更新所有 Key Setting 的相同值
- java - 如何在 Java 中使用带有 okhttp3 的 PUT 请求?
- kentico-12 - 如何使用 Kentico 将资产/图像添加到特定文件夹
- python - 烧瓶通天塔 | Flask 应用程序运行时重新加载 .mo 文件 | 生产
- javascript - 检查传入消息是否在属性内具有特定文本
- c# - 如果计算机中不存在,则安装 Ms Access