https://www.acmicpc.net/problem/10869
문제
풀이
🎯 Scanner 클래스를 사용하는 방법
String 입력 방법은 2가지가 있다. 차이점은 개행 문자를 무시하냐 안 하냐의 차이이다.
- in.next() : 문자열 입력 시 공백 전까지만 읽는다. (개행 문자 X)
- in.nextLine() : 문자열 입력시 Enter 입력 전까지만 읽는다. (개행 문자 O)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
int b = scan.nextInt();
System.out.printf("%d\n%d\n%d\n%d\n%d", a+b, a-b, a*b, a/b, a%b);
scan.close();
}
}
🎯 BufferedReader 사용하는 방법
BufferedReader의 경우 문자열을 받는 대표적인 방법은 readLine()과 read()이다. 둘의 차이는 readLine()은 한 행을 읽어오고, read()는 한 문자만 읽어온다. 그래서 특별한 경우가 없는 한 대부분 readLine()을 쓴다.readLine()은 한 행을 전부 읽기 때문에 공백단위로 입력해 준 문자열을 공백단위로 분리해주어야 문제를 풀 수 있다.
💬 문자열 분리 방법에는 2가지가 있다. 결론부터 말하자면 StringTokenizer 가 성능면에서 좋다.
1. StringTokenizer 클래스를 이용하여 분리해주는 방법
2. split() 을 이용하는 방법
먼저, StringTokenizer 클래스를 이용하여 분리해주는 방법으로 풀어보자.
객체 생성 할 때 StringTokenizer("문자열", 구분자);
구분된 변수를 꺼낼 때는 차례대로 nextToken();
이때 반환시킨 문자열은 반환됨과 동시에 해당 객체에서 사라지게 된다.
그리고 문자열을 반환했으니 Integer.parseInt()로 int 형으로 변환시켜준다.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
StringTokenizer st = new StringTokenizer(str, " ");
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
System.out.printf("%d\n%d\n%d\n%d\n%d", a+b, a-b, a*b, a/b, a%b);
}
}
두 번째 방법은 split() 을 이용하여 풀어보자.
br.readLine()을 통해 읽어 온 것을 split(" ") 하여 공백 단위로 나눠준 뒤 String 배열에 각각 저장해주면 된다. 배열에 저장된 원소들은 문자열이기 때문에 반드시 ing형으로 변환해줘야 한다.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] str = br.readLine().split(" ");
int a = Integer.parseInt(str[0]);
int b = Integer.parseInt(str[1]);
System.out.printf("%d\n%d\n%d\n%d\n%d", a+b, a-b, a*b, a/b, a%b);
}
}
실행 결과
백준에서 Scanner를 사용하여 입력을 받으면 시간 초과로 인해 문제를 못 푸는 경우가 있다. 그래서 BufferedReader를 사용하는 것을 권장한다.