• 카테고리

    질문 & 답변
  • 세부 분야

    알고리즘 · 자료구조

  • 해결 여부

    미해결

11. 임시반장 정하기 런타임 에러 관련 질문 드립니다.

23.12.15 20:24 작성 조회수 163

0

강사님 안녕하세요.

좋은 강의 잘 듣고 있습니다.

임시반장 정하기 문제에서 강사님이 작성해주신 코드와 동일하게 solution 메서드를 만들었다고 보이는데 런타임 에러로 나오는거 같습니다.

혹시 원인을 알 수 있을까요?
감사합니다.

 

import java.util.*;
  
public class Main {    
  
  public int Solution(int n, int[][] array) {  
      	int answer=0, max=Integer.MIN_VALUE; 
    	for(int i=1; i <=n; i++) {
        	int cnt = 0; 
          	for(int j=1; j<=n;j++) {
            	for(int k=1; k<=5;k++) {
                	if(array[i][k] == array[j][k]) {
                    	cnt++; 
                      	break; 
                    }
                }
            }
          	if(cnt>max) {
            	max = cnt; 
              	answer = i; 
            }
          
        }
    return answer; 
  }
  
  
  
  public static void main(String[] args) {
    Scanner in=new Scanner(System.in);
    int n = in.nextInt();
    Main T = new Main();        
    
    int[][] array = new int[n][n]; 
    
    
    for(int i = 0; i < n ; i++) {
    	for(int j = 0; j < n ; j++) {
        	array[i][j] = in.nextInt(); 
        }
    }            
    
    System.out.println(T.Solution(n, array)); 
    
  }
  
  
}

답변 1

답변을 작성해보세요.

0

안녕하세요^^

배열에 0번 인덱스부터 넣었으면 Solution 함수에서 i, j도 0번부터 인덱싱해야 합니다.

그리고 main에서 j for문은 5학년까지 이니까 0부터 4까지만 돌아야 합니다. 아래는 에러를 수정한 코드입니다.

import java.util.*;
  
public class Main {    
  
  public int Solution(int n, int[][] array) {  
      	int answer=0, max=Integer.MIN_VALUE; 
    	for(int i=0; i <n; i++) {
        	int cnt = 0; 
          	for(int j=0; j<n;j++) {
            	for(int k=0; k<5;k++) {
                	if(array[i][k] == array[j][k]) {
                    	cnt++; 
                      	break; 
                    }
                }
            }
          	if(cnt>max) {
            	max = cnt; 
              	answer = i+1; 
            }
          
        }
    return answer; 
  }
  
  
  
  public static void main(String[] args) {
    Scanner in=new Scanner(System.in);
    int n = in.nextInt();
    Main T = new Main();        
    
    int[][] array = new int[n][5]; 
    
    
    for(int i = 0; i < n ; i++) {
    	for(int j = 0; j < 5 ; j++) {
        	array[i][j] = in.nextInt(); 
        }
    }            
    
    System.out.println(T.Solution(n, array)); 
    
  }
  
  
}