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());
                }
    }
4

3 回答 3

1

您在代码中的哪个位置初始化表?那可能是那条线上唯一为空的东西。确保在声明 theTable 的地方也定义了它:

private int[][] theTable = new int[r][c]
于 2012-12-06T03:59:28.547 回答
1

添加:

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

就在for循环之前,如果您希望它在方法中是本地的。如果您希望它成为该类的成员,请添加

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

在您的班级中名列前茅。

于 2012-12-06T03:59:32.450 回答
0

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

于 2012-12-06T04:06:16.657 回答