数组中的空指针异常

数组中的空指针异常

本文介绍了数组中的空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在(见下文)处不断收到 NullPointerException 异常.在 C# 中一切正常,但在 android 中它坏了?

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

arrDBNumbers 已满,代码应该运行并计算 #1、#2、#3 等的数量到 #49 将 arrFreq[i][1] 加 1 以使用总计数填充 arrFreq号码.

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.

它通过 if 语句直到 k 达到 6,其中 arrDBNumbers[0][6] 为 1,然后跳转到 if 语句中,然后中断?我不确定这里发生了什么任何建议提前致谢 T

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 advicethanks 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?
            }
        }
    }
}

推荐答案

因为只是写

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

意味着你已经用所有 null 元素初始化了数组,因为它是一个 Integer 对象的数组,对象的默认值将是空引用.因此,

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++;

给出 NullPointerException.

如果您使用了一个原语数组,情况就不会如此,它默认为一个 0 数组.

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];

这篇关于数组中的空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 00:10