我有一些二传手。问题是,我想从用户准确输入错误的地方启动程序。
例如:如果用户在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
重复执行。
答案 0 :(得分:1)
您可以在/ 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");
答案 1 :(得分:0)
如果根据Exception来检查输入是否为不良输入的逻辑,则可以轻松地将读取的输入部分移至单独的方法中。
public String readInput(Scanner scn, String label) {
String returnValue = "";
while (true) {
try {
System.out.print(label + ": ");
returnValue = scn.next();
break;
} catch (Exception e) {
System.out.println("Value you entered is bad, please try again");
}
}
return returnValue;
}