我有一些二传手。问题是,我想从用户准确输入错误输入的地方启动程序。例如:如果用户提出了错误的输入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每次都会重复。
2 回答
慕的地8271018
TA贡献1796条经验 获得超4个赞
如果您检查输入是否错误的逻辑是基于异常的,您可以轻松地将读取输入部分移动到一个单独的方法中。
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;
}
添加回答
举报
0/150
提交
取消