Problem Solving

[백준/Java] 10951번 - EOF

Jintiago 2022. 3. 26. 18:51
import java.io.*;
import java.util.StringTokenizer;

public 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));
        StringTokenizer st;
        String input;
        
        while ((input = br.readLine()) != null) {
            st = new StringTokenizer(input);
            int a = Integer.parseInt(st.nextToken());
            int b = Integer.parseInt(st.nextToken());
            bw.write((a+b) + "\n");
        }
        bw.close();
    }
}

계속 런타임에러(NullPointer)가 뜨길래 왜 그런가 한참 고민했는데, 역시 같은 실수를 저질렀다.

while 문의 조건에 이미 readLine() 메소드가 들어가 있는데, 아래 실행문에 

st = new StringTokenizer(br.readLine());

를 넣었던 탓에 메소드가 중복되어 생긴 문제인 것 같다.

 

Scanner 클래스의 hasNext() 메소드를 이용해서도 풀어봤다.

import java.util.Scanner;

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();
    }
}