2012-12-06 42 views
1

我最初想说,感谢您花时间看我的文章。基本上我试图用Math.random创建一个随机整数的多维数组。代码编译并保持返回空指针异常错误消息。我不知道我在创建对象时做了什么错误。任何人都可以告诉我代码有什么问题吗?创建一个随机整数的多维数组

public Table(int r, int c) 
    { 
     rows = r; 
     columns = c; 

     for (int i = 0; i < r; i++) 
      for (int j = 0; j < c; j++) 
       { 
        /* 
        * Here is where the error keeps returning, blueJ keeps pointing 
        * me to this line of code and it has to be the variables I am using 
        * in the array that are causing the issue. The only issue is I      * don't know what to insert for that. 
        */ 
        theTable[i][j] = (int)(100*Math.random()); 
       } 
    } 
+2

我想你还没有初始化大小的表[i] [j]? – kosa

回答

1

你的代码在哪里初始化表?这可以是该行唯一的空值。确保在声明theTable,你把它定义为好:

private int[][] theTable = new int[r][c] 
1

地址:

int[][] theTable = new int[r][c]; 

for循环之前吧,如果你希望它是本地的方法。如果你想让它成为班级的成员,请在班级顶部添加

private int[][] theTable = new int[r][c]; 

0

您既不声明也不初始化theTable,所以对于Java而言,它不存在。当您尝试在Java中使用不存在的对象时,您将得到一个空指针异常。已经有正确的答案为您的问题提供解决方案。我建议你使用他们的代码。 durron597的特别清楚/好。

+0

如果你非常喜欢我的回答,为什么你不喜欢它? :-D – durron597

+0

哈哈好吧我现在就这样做。 – hologram