我有一些二傳手。問題是,我想從用戶準確輸入錯誤輸入的地方啟動程序。例如:如果用戶提出了錯誤的輸入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
提交
取消