[Java] Java 입력 2가지 (Scanner, BufferedReader)

조진우·2022년 10월 27일
0

Java

목록 보기
1/6
post-thumbnail

💡 방법 1. Scanner


보통 자바를 배운 사람들이 가장 많이 사용하는 입력 방법이다.
장점은 간편하지만, 속도가 느리다는 단점이 있다.
다음 아래와 같이 사용한다.

public class Bj10950_APlusBMinus3 {
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);

        int testCase = sc.nextInt();
        int arr[] = new int[testCase];

        for (int i = 0; i < testCase; i++) {
            int a = sc.nextInt();
            int b = sc.nextInt();
            arr[i] = a + b;
        }
        sc.close();

        for (int k : arr) {
            System.out.println(k);
        }
    }
}



💡 방법 2. BufferedReader


문자열로 입력해서 Int 형으로 변환할 Integer.parsInt를 해야한다는 번거로움이 있다.
하지만, 속도면에서 월등히 Scanner 보다 빠르다. 고로 알고리즘 풀 때는 BufferedReader를 사용하자.
사용하는 방법은 다음 아래와 같다.

public class Bj10950_APlusBMinus3 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();

        int testCase = Integer.parseInt(br.readLine());

        for (int i = 0; i < testCase; i++) {
            String str = br.readLine();

            StringTokenizer st = new StringTokenizer(str, " ");

            int a = Integer.parseInt(st.nextToken());
            int b = Integer.parseInt(st.nextToken());

            sb.append(a + b);
            sb.append("\n");

        }
        System.out.println(sb);
    }
}



참고자료


[백준] 10172번 : 개 - JAVA [자바]

profile
The Top of Iceblog

0개의 댓글