[Java] 백준 11021번 - A+B - 7
Java에서 BufferedReader와 StringTokenizer로 여러 테스트 케이스를 형식에 맞게 출력하는 방법을 정리했습니다.
For the English version of this post, see here.
[Java] 백준 11021번 - A+B - 7
풀이
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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));
int num = Integer.parseInt(br.readLine());
for(int i=0; i<num; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
bw.write("Case #" + (i+1) + ": " + (a+b) + "\n");
}
bw.flush();
bw.close();
}
}
StringTokenizer 위치
- 매 줄마다 새로 만들어야 함
- 반복문 안에 안 넣고, 반복문 전에 밖에서 한번만 만들게 된다면 -> 반복문에서 첫 줄만 읽게 되고, 이미 토큰을 다 써버려서 다음 반복에서
nextToken()할 게 없음 - 따라서, 반복문 안에 넣어서 반복할 때마다 새로운 토큰을 읽을 수 있도록 해야함
throws IOException
- 입력 읽다가 문제가 생길 때 ex) 입력 없음, 스트림 문제 ->
IOException이라고 함 - 이런 위험한 코드를 사용하면 -> 직접 처리(try-catch)하거나, 떠넘기기(throws) 해야함
throws IOException: 에러 나면 내가 처리 안 하고 넘긴다! (코테에서 많이 사용)