将值存储到字符串数组中

时间:2012-12-12 04:31:12

标签: java android arrays

我想将字符串数组中的值存储到另一个字符串数组中。但是我用下面的代码得到“NullPointerException”错误。 “imagesSelected”是一个存储有值的字符串数组。但是当我想在子字符串后将其移动到另一个字符串数组时,我得到错误。我相信是因为最后一行代码。我不知道如何让它发挥作用。

String[] imageLocation;

        if(imagesSelected.length >0){
        for(int i=0;i<imagesSelected.length;i++){
            int start = imagesSelected[i].indexOf("WB/");
            imageLocation[i] = imagesSelected[i].substring(start + 3);
        }
        }

5 个答案:

答案 0 :(得分:5)

你需要做这样的事情:

String[] imageLocation = new String[imagesSelected.length];

否则imageLocation将为null

顺便说一下,你的循环周围不需要if。它完全是冗余的,因为它将与循环开始时使用的逻辑相同。

答案 1 :(得分:4)

imageLocation [I]

你初始化了imageLocation吗?

我相信这个错误是因为你试图指向字符串数组中不存在的位置。 imageLocation [0,1,2,3 ...等]还不存在,因为字符串数组尚未初始化。

尝试String [] imageLocation [无论多长时间你想要数组]

答案 2 :(得分:2)

您必须为imageLocation分配内存。

imageLocation = new String[LENGTH];

答案 3 :(得分:1)

您的最终解决方案代码应如下所示,否则编译器会向您显示imageLocation未初始化的错误

    String[] imageLocation = new String[imagesSelected != null ? imagesSelected.length : 0];

    if (imagesSelected.length > 0) {
        for (int i = 0; i < imagesSelected.length; i++) {
            int start = imagesSelected[i].indexOf("WB/");
            imageLocation[i] = imagesSelected[i].substring(start + 3);
        }
    }

答案 4 :(得分:1)

看看这段代码

String[] imageLocation;

        if(imagesSelected.length >0){
          imageLocation = new String[imageSelected.length];
        for(int i=0;i<imagesSelected.length;i++){
            int start = imagesSelected[i].indexOf("WB/");
            imageLocation[i] = imagesSelected[i].substring(start + 3);
        }
        }
相关问题