본문 바로가기

알고리즘/백준

[백준] 10807 - 개수 세기

반응형

10807번 문제

 

구분된 정수를 배열에 넣고 비교하는 방식으로 문제를 풀면 된다. BufferedReader로 푸는 방법과 Scanner 클래스로 푸는 방법 2가지로 풀었다.

 

1. BufferedReader로 푸는 방법

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

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

        int n = Integer.parseInt(br.readLine());
        int total = 0;
        int[] num = new int[n];

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

        for(int i=0;i<n;i++){
            num[i] = Integer.parseInt(st.nextToken());
        }
        
        int v = Integer.parseInt(br.readLine());

        for(int j=0; j<num.length; j++){
            if(num[j] == v){
                total += 1;
            }
        }
        System.out.println(total);
        br.close();

    }
}

 

처음에 BufferedReader로 푸는데 자꾸 입력을 더 요구하거나 NumberFormatException 오류가 떠서 한참 삽질하다가 입력 순서도 바꾸고 이것저것 수정했더니 해결이 되었다...

 

2. Scanner 클래스로 푸는 방법

import java.util.*;

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

        int n = sc.nextInt();
        int[] num = new int[n];
        int total = 0;

        for(int i=0;i<n; i++){
            num[i] = sc.nextInt();
        }

        int v = sc.nextInt();

        for(int j=0;j<n;j++){
            if(num[j] == v){
                total++;
            }
        }
        System.out.println(total);
        sc.close();

    }
}

BufferedReader에서 헤맨 것과 달리 손쉽게 풀었다. 아직도 Scanner 클래스가 편해서 BufferedReader는 손이 잘 가지 않지만 메모리와 속도 차이가 크기 때문에 익숙해지려고 노력중이다..

반응형

'알고리즘 > 백준' 카테고리의 다른 글

[백준] 10818 - 최소, 최대  (0) 2024.02.13
[백준] 10871 - X보다 작은 수  (0) 2024.02.12
[백준] 10951 - A + B(4)  (0) 2024.02.10
[백준] 10952 - A + B (5)  (0) 2024.02.09
[백준] 2439 - 별 찍기(2)  (0) 2024.02.08