2014-10-10 80 views
0
import java.util.Scanner; 
public class TestMultiDimenArray 
{ 
    private static int row; 
    private static int column; 
    public static int [][] table1 = new int [row][column]; 

    public static int [][] get (int a, int b){ 
     row = a; 
     column = b; 
     Scanner keyboard = new Scanner(System.in); 
     for (int n = 0; n < a; n++){ 
      for (int m = 0; m < b; m++){ 
       table1[n][m] = keyboard.nextInt(); 
      } 
     } 
     return table1; 
    } 

    public static void display (int [][] array1){ 
     for (int n = 0; n < row; n++){ 
      for (int m = 0; m < column; m++){ 
       System.out.print(table1[n][m] + " "); 
      } 
      System.out.println(); 
     } 
    } 
    public static void main(String[] args){ 
      get(3,3); 
    } 
} 

程序編譯成功,但是當我運行它時,它返回錯誤。我該如何解決它?這就是我所能告訴我的問題。當我能夠告訴我的時候,系統有什麼問題告訴我要提供更多細節。錯誤:線程'main'中的異常java.lang.ArrayIndexOutOfBoundsException:0

+1

你嘗試調試程序?你認爲你正在用'public static int [] [] table1 = new int [row] [column];''做什麼?達到此聲明時,「row」和「column」的值是什麼? Java不是Excel ... – user2336315 2014-10-10 20:26:34

回答

3

此語句聲明長度0和寬度的2D陣列0

public static int [][] table1 = new int [row][column]; 

這是因爲rowcolumn和類時被初始化尚未被分配任何東西;只有在調用get時纔會分配它們。所以Java爲它們分配了默認值0

從參數中分配rowcolumn值後,初始化陣列。

public static int [][] table1; 

public static int [][] get (int a, int b){ 
    row = a; 
    column = b; 
    table1 = new int [row][column]; 
    Scanner keyboard = new Scanner(System.in); 
    // Rest unchanged 
} 
0

您不能設置動態的table1數組的大小。 確保a和b低於或等於原始和列。

(如果重新創建表1,我不認爲你將能夠獲得任何數據到它)