1 minute read


A+B - 4

두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오. 입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스는 한 줄로 이루어져 있으며, 각 줄에 A와 B가 주어진다. (0 < A, B < 10)

Input-1)
1 1
2 3
3 4
9 8
5 2

Output-1)
2
5
7
17
7

접근 방식

  • 해당 문제에서 핵심은 입력 종료 조건이 없다는 것이다. 그래서 더 이상 읽을 수 있는 데이터가 없다면 반복을 종료하라는 것으로 판단하였다.
  1. A, B는 공백으로 구분된다.
  2. EOF(읽을 수 없는 데이터) 가 존재할 경우 입력을 종료한다.

EOF 란? 데이터가 더이상 존재하지 않을 때 우리는 EOF (End of File) 즉, 파일의 끝이라고 한다.


문제 해결 과정

  • Scanner와 입력받는 방식과 BufferedReader로 입력받는 방식으로 풀어볼 것이다.


Scanner를 통한 풀이과정

  • Scanner 클래스의 hasNext() 메서드를 이용해 입력의 종료를 검증하였다. hasNext()나 hasNextInt() 둘중 아무거나 사용해도 무관하지만 nextInt()를 통해 정수를 입력받으니 hasNextInt()를 사용하였다.
    1
    2
    
    Scanner sc = new Scanner(System.in);
    while (sc.hasNextInt()) ...
    

Scanner 작성코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.util.Scanner;

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


BufferedReader를 통한 풀이과정

  • readLine을 통해 입력을 받아 input에 저장된 값이 null일 경우 입력의 종료라고 판단하고 반복문을 종료하도록 작성하였다.
    1
    2
    
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    while((input = br.readLine()) != null) ...
    

BufferedReader 작성코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;

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


회고

  • Python으로는 손쉽게 풀수 있었으나 Java로 풀어보니 EOF를 고려하지 않을 수 없었다. 그래서 EOF에 대해서 다시 복습할 수 있었다.
  • 그리고 입력값이 많아질수록 Scanner보다 BufferedReader가 실행 속도에 있어서 메리트가 있음을 알게 되었다.