nextXXX() 메소드 후에 nextLine() 메소드를 사용했을 때의 Scanner의 문제

조회수 9689회

Scanner의 메소드인 nextInt()nextLine()을 키보드 입력을 받기 위해 다음과 같이 사용하고 있습니다.

System.out.println("enter numerical value");    
int option;
option = input.nextInt();//read numerical value from input
System.out.println("enter 1st string"); 
String string1 = input.nextLine();//read 1st string (this is skipped)
System.out.println("enter 2nd string");
String string2 = input.nextLine();//read 2nd string (this appears right after reading numerical value)

문제는 다음의 결과와 같이, 수치값을 입력한 후에, 처음 input.nextLine()이 실행되지 않고 두번째 input.nextLine()이 실행된다는 것입니다.

Enter numerical value
3//this is my input
enter 1st string//the program is supposed to stop here and wait for my input, but is skipped
enter 2nd string//and this line is executed and waits for my input

테스트 해 보았고, 이 문제는 input.nextInt() 때문에 발생하는 것 같습니다. 그래서 그것을 지우고 실행하보니, string1 = input.nextLine()string2 = input.nextLine()이 제가 기대한 것처럼 잘 실행됩니다. 도대체 무슨 문제일까요?

1 답변

  • 좋아요

    1

    싫어요
    채택 취소하기

    그 이유는 Scanner#nextInt 메소드는 사용자 입력의 가장 마지막 개행문자 (newline)를 제거하지 않기 때문입니다. 즉, 개행문자 전까지를 숫자로 읽어드리는 것입니다. 그래서 그 개행문자는 그 다음에 호출된 Scanner#nextLine() 메소드의 입력으로 처리된 것이지요.

    해결책:

    • Scanner#nextInt를 호출한 후에 개행문자를 제거하기 위해 Scanner#nextLine을 한 번 더 실행시키면 됩니다.
    int option = input.nextInt();
    input.nextLine();  // Consume newline left-over
    String str1 = input.nextLine();
    
    • 좀 더 좋은 방법을 생각해 본다면, 사용자의 입력을 Scanner#nextLine을 사용해서 입력받고 그 문자열을 Integer#parseInt(String) 메소드를 사용해서 숫자로 변환하는 방법이 있습니다.
    int option = 0;
    try {
        option = Integer.parseInt(input.nextLine());
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }
    String str1 = input.nextLine();
    

    Scanner#next() 또는 Scanner#nextFoo 메소드를 실행한 후에 Scanner#nextLine을 사용한다면 위와 같은 똑같은 상황이 계속될 것입니다.

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)