- [백준] 숫자 카드 - 108152025년 01월 07일 18시 18분 46초에 업로드 된 글입니다.작성자: do_hyuk728x90반응형
https://www.acmicpc.net/problem/10815
해당 문제는 간단하게 생각해서 Set에 상근이가 가지고 있는 N개의 카드를 저장해 두고 M개의 카드들 중 뭐가 맞고 틀린지 판단해주는 쉬운 문제이다.
정답 코드
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.HashSet; import java.util.StringTokenizer; class Main { private static final HashSet<Integer> nums = new HashSet<>(); public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); StringTokenizer st; int N = Integer.parseInt(br.readLine()); st = new StringTokenizer(br.readLine(), " "); for (int n = 0; n < N; n++) { nums.add(Integer.parseInt(st.nextToken())); } int M = Integer.parseInt(br.readLine()); st = new StringTokenizer(br.readLine(), " "); for (int m = 0; m < M; m++) { int question = Integer.parseInt(st.nextToken()); bw.write(isExist(question) + " "); } bw.flush(); bw.close(); } private static int isExist(int question) { if (nums.contains(question)) { return 1; } return 0; } }
겪었던 문제
기존에 작성했던 코드를 보자면
public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); StringTokenizer st = new StringTokenizer(br.readLine(), " "); int N = Integer.parseInt(br.readLine()); for (int n = 0; n < N; n++) { nums.add(Integer.parseInt(st.nextToken())); } ... }
StringTokenizer 를 N 보다 먼저 선언을 했었다. 하지만 먼저 선언한 뒤 실행을 했을 때 NumberFormatException 이 발생했다.
그 이유는 N을 먼저 읽은 후 상근이의 카드들을 " "을 기준으로 읽어야 하는데 st를 먼저 선언했기 때문에 st가 비어있다 판단하고 NumberFormatException가 발생한 것이다.
다음부터는 N개의 값을 읽기 위해 StringTokenizer를 초기화해야 겠다.
728x90반응형'코딩문제' 카테고리의 다른 글
[소프티어] GPT식 숫자 비교 (1) 2025.01.22 [백준] 퇴사 - 14501 (0) 2025.01.10 [백준] N과 M (4) - 15652 (0) 2025.01.09 [백준] 큐2 - 18258 (0) 2025.01.09 백준 1260번: 그래프 탐색 (DFS와 BFS) (1) 2024.12.14 댓글