0

文字列配列の値を別の文字列配列に格納したかったのです。しかし、以下のコードで「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);
        }
        }
4

5 に答える 5

5

次のようなことをする必要があります:

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

それ以外の場合imageLocationは になりますnull

ちなみに、ifループの周りは必要ありません。ループの開始時に使用されるのと同じロジックになるため、完全に冗長です。

于 2012-12-12T04:34:31.363 に答える
4

画像の場所[i]

imageLocation を初期化しましたか?

このエラーは、存在しない文字列配列内の場所を指そうとしているためだと思います。文字列配列が初期化されていないため、imageLocation[0,1,2,3...etc] はまだ存在しません。

String[] imageLocation[配列をどれだけ長くしたいか]を試してください

于 2012-12-12T04:41:36.870 に答える
2

imageLocation にメモリを割り当てる必要があります。

imageLocation = new String[LENGTH];
于 2012-12-12T04:34:24.490 に答える
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);
        }
        }
于 2012-12-12T04:41:08.570 に答える
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);
        }
    }
于 2012-12-12T04:38:21.547 に答える