2014-10-10 112 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,我不认为你将能够获得任何数据到它)

相关问题