2014-01-25 2 views
0
int[][] input = new int[3][]; 
int count = 1; 

for(int i = 0; i <= 2 ; i++) { 
    for(int j = 0; j <= 2; j++) { 
     input[i][j] = count++; 
    } 
} 

다섯 번째 줄은 오류가 발생합니다.다음 자바 코드 조각이 런타임 오류를 발생시키는 이유는 무엇입니까?

+3

배열의 두 번째 차원을 초기화하지 않았습니다. 'int [] [] input = new int [3] [3];' –

+0

중복 : http://stackoverflow.com/questions/12231453/creating-two-dimensional-array –

+0

@ user3167973 내 대답이 도움이된다면 내 대답을 선택하십시오. – Ashish

답변

0
int[][] input = new int[3][]; 

이라고합니다. 에 크기를 각각 에 대해 정의해야합니다. 같은 :

input[0]=new int[2];//for row 1 (row 1 contain 2 column) 
input[1]=new int[5];//for row 2 (row 2 contain 5 column) 
input[2]=new int[1];// for row 3 (row 3 contain 1 column) 

그래서 당신은

/* 비정형 배열 은 행이 COLS의 다른 어떤이있는 에서 다차원 배열되어 원하는대로 각 행에 대해 열 크기를 정의합니다.

class Ragged 
    { 
    public static void main(String args[]) 
    { 
     //declaration of a ragged array 
     int arr[][] = new int[3][]; 
     //declaration of cols per row 
     arr[0] = new int[4]; 
     arr[1] = new int[2]; 
     arr[2] = new int[3]; 

     int i, j; 

     for(i =0; i< arr.length; i++) 
     { 
     for(j =0 ; j< arr[i].length; j++) 
     { 
      arr[i][j] = i + j+ 10; 
     } 
     } 

     for(i =0; i< arr.length; i++) 
     { 
     System.out.println();//skip a line 
     for(j =0 ; j< arr[i].length; j++) 
     { 
      System.out.print(arr[i][j] + " "); 
     } 
     } 




//-------------more---------------- 
    int temp[];//int array reference 
    //swap row2 and row3 of arr 
    temp = arr[1]; 
    arr[1] = arr[2]; 
    arr[2] = temp; 


    System.out.println();//skip a line 
    for(i =0; i< arr.length; i++) 
    { 
    System.out.println();//skip a line 
    for(j =0 ; j< arr[i].length; j++) 
    { 
     System.out.print(arr[i][j] + " "); 
    } 
    } 

}//main 
}//class 

/* * /

은 불규칙 배열이없는 최종 치수의 발 와 다차원 배열을 정의 선언.

명시 적으로 모든 행의 마지막 크기 인 의 크기를 정의하십시오. */

0

당신은 두 번째 차원

1) int[][] input = new int[3][3];

또는

2

)

for(int i = 0; i <= 2 ; i++){ 
    input[i] = new int[3]; 
} 
0

은 당신이 두 번째 배열 차원이 지정되어 있지 않기 때문에 초기화 할 필요가있다.

이 실행해야합니다 : 두 번째 차원의 크기를 지정하지 않았기 때문에

int[][] input = new int[3][3]; 
    int count = 1; 
    for(int i = 0; i <= 2 ; i++){ 
     for(int j = 0; j <= 2; j++){ 
      input[i][j] = count++; 
     } 
    } 

executable 예를

0

를 참조하십시오.

1

배열의 두 번째 차원이 비어 있습니다.

int[][] input = new int[3][]; 

이 시도 : 배열의이 유형은 불규칙 배열

int[][] input = new int[3][3]; 
0

초기화하는 동안 두 번째 배열의 크기를 지정해야합니다. 또한 배열의 .length 속성을 사용하여 하드 코딩 된 크기를 피할 수 있습니다.

int[][] input = new int[3][3]; 
int count = 1; 

for(int i = 0; i <= input.length ; i++) { 
    for(int j = 0; j <= input[i].length; j++) { 
     input[i][j] = count++; 
    } 
} 
관련 문제