2014-01-25 61 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++; 
    } 
} 

第五行發出錯誤。爲什麼下面這段java代碼會引發運行時錯誤?

+3

您沒有初始化數組的第二維。 'int [] [] input = new int [3] [3];' –

+0

duplicate: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 

/* 聲明一個參差不齊的陣列限定與最後一維缺失的VAL 一個 多維數組。

明確定義了所有行的最後一個維的大小 。 */

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++; 
    } 
} 
相關問題