본문 바로가기

JAVA

EOF(End of File)란? 자바 커맨드에서 EOF처리하기 (백준 10591 자바 코드)

EOF는 입력의 개수가 주어지지 않고 입력값만 들어오는 경우, 입력(파일)이 끝났다는 것을 어떻게 알아낼 것이냐에 대한 개념이다. 개수를 모르므로 FOR문보다는 WHILE문을 이용한다.

EOF는 간단하게 처리할 수 있다. 새롭게 라인을 읽어왔는데 그 값이 null이면 더 이상 읽을 것이 없다는 의미이므로 루프를 끝내면 된다. (예제 코드 참고)

자바에서 커맨드라인을 이용해 입력값을 주는 경우, CTRL+Z를 누른 뒤 엔터키를 누르면 입력이 끝난 것으로 처리된다.

 

< 백준 10591번 A+B - 4 정답 코드 >

import java.io.*;

class Main{
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        
        String line = br.readLine();
        int pos,a,b = 0;
        
        while(line != null){	// EOF handling
            pos = line.indexOf(" ");
            a = Integer.parseInt(line.substring(0,pos));
            b = Integer.parseInt(line.substring(pos+1));
        
            bw.write(Integer.toString(a+b));
            bw.newLine();
            
            line = br.readLine();
        }
        bw.flush();
    }    
}