Algorithm/BOJ

[BOJ - Silver II] 생태학 / ⭕

cks._.hong 2024. 8. 19. 20:55

생태학

 

1. 제출 코드 (15분 21초 / 자료구조(Map))

import java.util.*;

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

        Map<String, Integer> map = new HashMap<>();
        String input;
        int cnt = 0;
        while(sc.hasNext()) {
            input = sc.nextLine();
            map.put(input, map.getOrDefault(input, 0) + 1);
            cnt++;
        }
        List<String> keySet = new ArrayList<>(map.keySet());
        Collections.sort(keySet);

        for(String key : keySet) {
            System.out.printf("%s %.4f\n", key, ((double) map.get(key) / (double) cnt) * 100);
        }
    }
}

 

2. 구현 로직

  1. 해시맵을 생성하고 String, Integer로 입력받은 것을 저장
  2. Key만 가져와서 정렬
  3. 해시맵에 있는 Value와 cnt를 이용해서 정답 출력

3. 유의할 점

  • BufferedReader를 이용해서 하니까 입력해서 NullPointException이랑 noSuchElement 에러가 발생한다.
  • Scanner를 이용해서 입력을 받아야 한다!