백준 5635번 생일-JAVA

sujin·2025년 3월 23일

코딩테스트-백준

목록 보기
14/18

📝문제

📝알고리즘

//n개의 줄에 학생 정보를 입력받아 배열 info의 각 행의 0~3열에 이름, 생일 일, 월, 연도를 저장함
//연도인 info[i][3]을 기준으로 오름차순 정렬
//info[i][3]이 동일하면 월인 info[i][2]를 기준으로 오름차순 정렬
//info[i][2]가 동일하면 일인 info[i][1]을 기준으로 오름차순 정렬
//가장 나이가 적은 사람의 이름인 info[N-1][0]출력
//가장 나이가 많은 사람의 이름인 info[0][0] 출력

❌틀린 코드

import java.io.*;
import java.util.*;

public class Main{
    public static void main(String[] args)throws IOException{
        BufferedReader rd=new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st=new StringTokenizer(rd.readLine());
        int N=Integer.parseInt(rd.readLine());
        String[][] info=new String[N][4];
        for(int i=0; i<N;i++){
            info[i][0]=st.nextToken();
            info[i][1]=st.nextToken();
            info[i][2]=st.nextToken();
            info[i][3]=st.nextToken();
            
        }
        Arrays.sort(info, new Comparator<String[]>(){
            public int compare(String[] o1, String[] o2){
                if(o1[3].equals(o2[3])){
                    if(o1[2].equals(o2[2])){
                        return Integer.parseInt(o1[1])-Integer.parseInt(o2[1]);
                    }
                    return Integer.parseInt(o1[2])-Integer.parseInt(o2[2]);
                }
                return Integer.parseInt(o1[3])-Integer.parseInt(o2[3]);
            }
            
        });
        System.out.println(info[N-1][0]+"\n"+info[0][0]);
    }
}

📝틀린 이유

StringTokenizer를 사용하려고 할 때 첫 번째 rd.readLine()으로 한 줄을 읽고 그 줄에 대해 토큰을 나누려는 의도였는데 두 번째 rd.readLine()을 또 호출하면서 st.nextToken()이 제대로 동작하지 못함➡️각각의 입력을 처리할 때마다 새로운 StringTokenizer를 생성하도록 수정함

✅수정한 코드

import java.io.*;
import java.util.*;

public class Main{
    public static void main(String[] args)throws IOException{
        BufferedReader rd=new BufferedReader(new InputStreamReader(System.in));
        int N=Integer.parseInt(rd.readLine());
        String[][] info=new String[N][4];
        for(int i=0; i<N;i++){
            StringTokenizer st=new StringTokenizer(rd.readLine());
            info[i][0]=st.nextToken();
            info[i][1]=st.nextToken();
            info[i][2]=st.nextToken();
            info[i][3]=st.nextToken();
            
        }
        Arrays.sort(info, new Comparator<String[]>(){
            public int compare(String[] o1, String[] o2){
                if(o1[3].equals(o2[3])){
                    if(o1[2].equals(o2[2])){
                        return Integer.parseInt(o1[1])-Integer.parseInt(o2[1]);
                    }
                    return Integer.parseInt(o1[2])-Integer.parseInt(o2[2]);
                }
                return Integer.parseInt(o1[3])-Integer.parseInt(o2[3]);
            }
            
        });
        System.out.println(info[N-1][0]+"\n"+info[0][0]);
    }
}
profile
열공!

0개의 댓글