NullPointerException in array

2019-03-07 02:52发布

I keep getting a NullPointerException at (see below). Everything works fine in C#, but in android it breaks?

arrDBNumbers is full and code is supposed to run through and count the amount of #1, #2, #3 and so on to #49 adding 1 to arrFreq[i][1] to fill arrFreq with the total count of the numbers.

It runs through the if statement till k hits 6 where arrDBNumbers[0][6] is 1, then jumps inside if statement and then breaks? I'm not sure whats going on here any advice thanks in advance T

Integer[][] arrDBNumbers = new Integer[100][8];
Integer[][] arrFreq = new Integer[49][2];


for (int i = 0; i < 49; i++){
    for (int j = 0; j < 49; j++){
        for (int k = 1; k < 7; k++){
            if (arrDBNumbers[j][k] == (i + 1)){
                arrFreq[i][1]++;     //  < here is where I get Exception?
            }
        }
    }
}

2条回答
相关推荐>>
2楼-- · 2019-03-07 03:26

Integer is a container for int, in your case you have lots of null objects. if you use int instead it will work as you expect.

查看更多
走好不送
3楼-- · 2019-03-07 03:33

Because just writing

Integer[][] arrFreq = new Integer[49][2];

means you have initialized the array with all null elements because it is an array of Integer Objects and Object's default value will be null reference. Hence,

arrFreq[i][1]++;  // trying null++;

gives NullPointerException.

This wouldn't have been the case if you had used an array of primitives, which will default to an array of 0s.

int[][] arrFreq = new int[49][2];
查看更多
登录 后发表回答