Coding Test

[Coding Test] 프로그래머스 1단계 - 추억 점수

한비Skyla 2024. 10. 28. 19:00

📚 문제

 

✏️ 메모 

Index 0 out of bounds for length 0

왜 이런 오류가 생기는 고....

 

answer 배열이 빈 배열로 초기화되어 있기 때문...

int[] answer = {};

 

ㅋㅋㅋㅋㅋㅋ

너무 오랜만에 해서 이런 실수를....

 

int[] answer = new int[photo.length]; 로 바꿔줘야 함. 

 

 

[JAVA]자바 프로그래밍에서 'Index 0 out of bounds for length 0' 오류 이해와 해결법

안녕하세요, 프로그래밍 세계에 오신 것을 환영합니다! 오늘은 자바 프로그래밍에서 자주 마주치는 오류 중 하나인 ‘Index 0 out of bounds for length 0’에 대해 알아보겠습니다. 이 포스트를 통해 해

wyatti.tistory.com

 

 

🔎 문제해결

import java.util.*;

class Solution {
    public int[] solution(String[] name, int[] yearning, String[][] photo) {
        int[] answer = new int[photo.length];

        // name[i] 의 yearing 점수는 yearning[i]
        HashMap<String, Integer> scoreMap = new HashMap<>();
        for (int i = 0; i < name.length; i ++) {
            scoreMap.put(name[i], yearning[i]);
        }


        // for 문을 돌면서 photo[0][0] 부터 보면서 name[0]이랑 같은지 아닌지 확인
        for (int i = 0; i < photo.length; i ++) {
            int totalScore = 0;
            // photo[i][0] - photo[i][j]까지 순회하며 socre의 key 값과 같은 
            // name이 있는지 확인
            for (int j = 0; j <photo[i].length; j++) {
                // 같은 name 이 있으면 그 key의 value 값을 더해서 answer 에 추가.
                if (scoreMap.containsKey(photo[i][j])) {
                    totalScore += scoreMap.get(photo[i][j]);
                }
            }
            answer[i] = totalScore;
        }

        return answer;
    }
}