티스토리 뷰

JAVA

Scanner nextInt(), nextLine()

seoca 2019. 7. 10. 02:49

A user types 'integer value' and 'Enter', but nextInt() does not use the end of the input, which is 'Enter' so that it leaves in the buffer. If nextLine() is used after nextInt(), the remainder causes an error. Because nextLine() is the method that reads data until the 'Enter' input. To remove the last input(Enter), simply use nextLine() to terminate the line. 

 

nextInt()메서드 다음에 nextLine()메서드가 온다면 Enter키가 input으로 들어올 때 까지 데이터를 읽기 때문에 nextInt()의 input data 다음의 enter 까지 읽어들이게 된다. 자연스럽게 그 다음 nextLine() 메서드는 실행이 되어지지 않고 종료되게 된다. 그런 결과를 대비하기 위해 꼭 enter input을 비우기위한 nextLine()을 nextInt()다음에 써주어야한다. nextInt()다음에 다른 nextInt()가 사용된다면 상관없다. 

 

 int select = MenuViewer.keyboard.nextInt();
  MenuViewer.keyboard.nextLine(); //nextInt 다음에 nextLine 으로 delimiter 지우기.