본문 바로가기
Study/[Algorithm]

[백준] 10951번 JAVA - EOF(End Of File)

by Nameless 2021. 5. 20.

 


1. 목적

 파일의 끝(EOF)을 올바르게 판단하는 법을 연습한다.

 총 몇 줄이 주어진다 등의 정보는 입력으로 주지 않는다. 

 

1-1. EOF란?

 EOF(End Of File, 파일끝) 처리로 끝낸다.

- EOF란 : 데이터 소스로부터 더 이상 읽을 수 있는 데이터가 없음을 나타낼때를 말한다.

             입력부분의 기준이 없는 문제를 접할 때 사용할 수 있다.

자바에서는 hasNextLine()과 NextLine을 사용한다.(Scanner 이용)

 

2. 방법(JAVA)

- (Java) Scanner의 메서드들은 NoSuchElementException을 던진다.

- (Java) BufferedReader.readLine()은 null을 반환한다.

 

 

① Scanner 사용

 - Scanner 로 입력을 받는다.

 - 입력받는 값이 있으면 A,B 입력받고 합을 출력하는 과정을 반복한다.

 - hasNext(), hasNextInt() 사용 가능

 

public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        
        while (sc.hasNext()) {
            int a = sc.nextInt();
            int b = sc.nextInt();
            
            System.out.println(a+b);    
        }
        sc.close();
    }
}

 

② BufferedReader 사용

 

public class Main {
    public static void main(String[] args) throws IOException{
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String input = "";
    
        while((input=br.readLine())!=null) {
            StringTokenizer st = new StringTokenizer(input);
            int a = Integer.parseInt(st.nextToken());
            int b = Integer.parseInt(st.nextToken());
            bw.write(String.valueOf(a+b));
            bw.newLine();
        }
        bw.flush();
        bw.close();
        br.close();
    }
}
 

댓글