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 답변
-
그 이유는
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
을 사용한다면 위와 같은 똑같은 상황이 계속될 것입니다.
댓글 입력