for循环中的空指针异常

时间:2013-05-10 14:05:06

标签: java for-loop syntax arrays

我尝试通过将数组放入for循环来获取我不希望从字符串数组中获取的字符串。

我尝试以下代码,但是我得到了java.lang.NullPointerException,我不知道为什么。

感谢帮助。

String unWanted = new String[]{"","a","b","c"};

String[] temp = new String[unWanted.length-1];
int p = 0;
for (int k = 0; k < unWanted.length; k++){
    if(unWanted[k].equals("") == false)
    {
        temp[p] = unWanted[k];
        p++;
    }
}

4 个答案:

答案 0 :(得分:5)

这里唯一的错误是String数组声明

String[] unWanted = new String[]{"","a","b","c"};

答案 1 :(得分:4)

temp的长度为3,但您在循环中的位置4处插入值。

答案 2 :(得分:2)

首先更改此行

String unWanted = new String[]{"","a","b","c"};

String[] unWanted = new String[]{"","a","b","c"};

答案 3 :(得分:2)

甚至是编译?

String unWanted = new String[]{"","a","b","c"};

更改为

 String[] unWanted = new String[]{"","a","b","c"};

更改后,console中没有 NullPointerException 。它工作正常