Java - if 조건문 안에 hasNextInt()

girean·2020년 12월 2일
0

java

목록 보기
2/4
import java.util.*;
class practice {
         public static void main(String[] args) {
              Scanner reader = new Scanner(System.in);
              if(reader.hasNextInt()){
                  int numberEntered = reader.nextInt();
              }
         }
}

if의 조건문에 hasNextInt()가 있다.
if문에 도달하기 전에 입력받은 것은 없다.
어떻게 if문에 들어갈수 있을까?

그 이유는,

public boolean hasNextInt() {
       ...
       boolean condition = false;
       while(!condition) {
           ...
       }
       ...
       return stuff;
}

hasNextInt()라는 메소드가 호출되면, 입력을 기다리고 있는 상태다.
입력을 받게 될 경우, 그 값이 int이면 true를 리턴하고 입력받은 값을 버리지 않고
다음 nextInt()에 던져준다.

profile
Developer

0개의 댓글