0

配列を分割しようとして、ある部分をある配列に格納し、他の部分を別の配列に格納しようとしています。次に、2を反転して新しい配列に保存しようとしています。ここに私が持っているものがあります

public int[] flipArray(){
        int value = 3;
        int[] temp1 = new int[value];
        int[] temp2 = new int[(a1.length-1) - (value+1)];
        int[] flipped = new int[temp1.length+temp2.length];

    System.arraycopy(a1, 0, temp1, 0, value);
    System.arraycopy(a1, value+1, temp2, 0, a1.length-1);
    System.arraycopy(temp2, 0, flipped, 0, temp2.length);
    System.arraycopy(temp1, 0, flipped, temp2.length, temp1.length); 
            return flipped;
    }
    private int[]a1={1,2,3,4,5,6,7,8,9,10};
4

4 に答える 4

1

[0, length - 1] の範囲外の配列要素にアクセスしようとすると、ArrayIndexOutOfBoundsException が発生します。

デバッガーを使用するか、System.arraycopy の各呼び出しの前に System.out.println(text) を配置して、コピー元とコピー先の配列の配列長と要素数を出力すると、問題を自分で見つけることができます。コピー

于 2012-12-02T22:08:10.933 に答える
0

この行は間違っています:

System.arraycopy(a1, value+1, temp2, 0, a1.length-1);

位置4から開始し、9つの要素をコピーします。これは、配列内のインデックス4から12に要素をコピーしようとすることを意味します。

于 2012-12-02T22:09:55.887 に答える
0

インデックスと配列の長さがオフです:

public int[] flipArray(){
    int value = 3;
    int[] temp1 = new int[value];
    int[] temp2 = new int[a1.length - value];
    int[] flipped = new int[a1.length];

    System.arraycopy(a1, 0, temp1, 0, value);
    System.arraycopy(a1, value, temp2, 0, temp2.length);
    System.arraycopy(temp2, 0, flipped, 0, temp2.length);
    System.arraycopy(temp1, 0, flipped, temp2.length, temp1.length); 
    return flipped;
}
private int[]a1={1,2,3,4,5,6,7,8,9,10};

System.arraycopy重要なのは、最後のインデックスで要素をコピーしないことを理解することです。

于 2012-12-02T22:07:19.430 に答える
0

インデックスを使った不要な操作を取り除きます:

public int[] flipArray(){
int value = 3;
int[] temp1 = new int[value];
int[] temp2 = new int[a1.length - value];
int[] flipped = new int[temp1.length+temp2.length];

System.arraycopy(a1, 0, temp1, 0, value);
System.arraycopy(a1, value, temp2, 0, temp2.length);
System.arraycopy(temp2, 0, flipped, 0, temp2.length);
System.arraycopy(temp1, 0, flipped, temp2.length, temp1.length); 
}
于 2012-12-02T22:07:47.160 に答える