我有一些二传手。问题是,我想从用户准确输入错误输入的地方启动程序。例如:如果用户提出了错误的输入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每次都会重复。
慕的地8271018
相关分类