2016-11-07 4 views
1

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()); 
     } 
    } 
} 

답변

5

사용자가 숫자를 입력 할 수 없습니다. 그들이 할 때 당신은 그것을 처리해야합니다. 대신 숫자를 읽는의

는 루프에서 문자열을 읽어들이는 번호를 입력하면

  • 는, 정수로 구문 분석 번호를 사용하고, 반복 중지합니다.
  • 다른 사람이 입력하면 메시지를 인쇄하고 계속 반복합니다. 이 같은

뭔가 :

while (true) { 
    String line = keyboardIn.nextLine(); 
    if (line.matches("\\d+")) { 
    int d = Integer.parseInt(line); 
    dateOpened.setDay(d); 
    break; 
    } 

    System.out.println("Must be an integer; try again."); 
} 
1

나는이 숙제 질문 추측은 그래서 당신에게 정확한 답을주지해야한다. 단어를 여기에 보면 자세한 내용

if (input.hasNextInt()) { 
    int number = input.nextInt() ; 
    System.out.println(number); 
    //your code 
} else { 
    System.out.println("Sorry please enter a number!"); 
} 

: : :
1. How do I keep a Scanner from throwing exceptions when the wrong type is entered?
2 How to use Scanner to accept only valid int as input

+1

아무도 downvote를 설명 할 수 있습니까? –

+0

숫자가 아닌 입력으로 작성한 코드를 사용해 보셨습니까? –

+0

int가 아닌 값이 소비되지 않으므로이 방법은 작동하지 않습니다. – kgeorgiy

0

를이 문장에서 "널 입력 계정이 열린 날"하지만 당신은 다음을 사용할 수 있습니다 catch 섹션에서 null이옵니다, e.getMessage. 잘못된 유형의 키를 입력 할 때 계속 사용자가 번호를 입력하게하려는 경우.

try 부분에서 변수를 다시 초기화해야합니다. 데모 코드는 다음과 같습니다. 이미 테스트를 마쳤습니다. 제대로 작동합니다.

import java.util.Scanner; 

public class Question01 { 

    public static void main(String[] args) { 

     // new Scanner(System.in) 
     boolean success = false; 
     Object d = null; 
     while (!success) { 
      try { 

       System.out.print("Enter the day the account opened: "); 
       Scanner keyboardIn = new Scanner(System.in); 
       d = keyboardIn.nextInt(); 

       System.out.println(d); 

       success = true; 
      } catch (Exception e) { 

       System.out.println("Error"); 
       // keyboardIn.close(); 
      } 
     } 

    } 
} 
+0

위의 코드를 내 메서드에 통합하려면 어떻게해야합니까? – Daniel

+0

catch 클래스에서 e.getMessage()를 호출하여 Date 클래스의 오류 메시지를 호출하여 범위가 유효하지 않음을 명시해야합니다. 예 : 1-31과 1-12 사이. – Daniel

+0

e.getMessage()를 코드에 유지하면 기존 함수에 영향을 미치지 않습니다. 날짜 또는 월 형식을 확인하는 자세한 요구 사항에 대해서는이 객체가 "dateOpened"객체에 정의되어 있다고 생각합니다. 볼 수 없기 때문에 더 많은 주석을 달 수 있습니다. – lpcclown

관련 문제