String 또는 Char를 입력 할 때마다 내 read() 메소드가 충돌합니다. 정수 값만 받아들이면 어떻게 될까요? int를 입력하면 잘 동작하지만 Char 나 String을 입력하면 반복적 인 "Enter the day the account opened : null"오류가 발생합니다. 프로그램을 종료하려면 프로그램을 종료해야합니다.이 read() 메서드에서 사용자가 String을 입력하는 것을 어떻게 중지합니까?
private void readDay(Scanner keyboardIn) {
boolean success = false;
while (!success) {
try {
System.out.print("Enter the day the account opened: ");
int d = keyboardIn.nextInt();
dateOpened.setDay(d);
success = true;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
// Enter the month, checking for error
private void readMonth(Scanner keyboardIn) {
boolean success = false;
while (!success) {
{
try {
System.out.print("Enter the month the account opened: ");
int m = keyboardIn.nextInt();
dateOpened.setMonth(m);
success = true;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
}
// Enter the year, checking for error
private void readYear(Scanner keyboardIn) {
boolean success = false;
while (!success) {
try {
System.out.print("Enter the year the account opened: ");
int y = keyboardIn.nextInt();
dateOpened.setYear(y);
success = true;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
아무도 downvote를 설명 할 수 있습니까? –
숫자가 아닌 입력으로 작성한 코드를 사용해 보셨습니까? –
int가 아닌 값이 소비되지 않으므로이 방법은 작동하지 않습니다. – kgeorgiy