본문 바로가기

Studying JAVA/백준

[1단계]입출력받아보기 - nextLine() vs hasNextLine()

nextLine() 메소드와 hasNextLine() 메소드에 대해서 알아보겠다.


nextLine()



Java API를 찾아보니 nextLine()  메소드는 


This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.


끝의 구분자를 제외하고 현재라인의 나머지를 리턴한다고 명시되어있다.


이말은 엔터만을 감지하여 엔터 전까지의 모든것을 입력받겠다! 



hasNextLine()



hasNextLine() 메소드는 형태부터 다르다. 형태가 boolean으로 참,거짓을 판별하는 메소드이다.


Returns true if there is another line in the input of this scanner. This method may block while waiting for input. The scanner does not advance past any input.

입력이 다음 라인에 있으면 True를 반환한다. 이 메소드는 입력을 기다리는 동안 막는다. 


이말은 다음줄에 입력이 있는지 여부를 판단해 입력이 있으면 True를, 없다면 False를 반환한다. 


*입력이 있을때까지 기다렸다가 True를 반환하기 때문에  close()로 닫아주지 않으면 무한루프에 빠질 수 있다.*