2016-12-21 5 views
0

Also wenn ich eine int [3] [3] temp1 und eine int [3] [3] temp2 habe, beide gefüllt, wie würde ich sie kombinieren, um eine temp1and2 [6] [3] zu machen? Ich versuche ein Gitterfeld zu spleißen, wobei x das zu spleißende Array ist und y die Spalte ist, die ich entfernen möchte. Ich versuchteWie kombiniere ich Grid-Arrays?

public static int[][] splice(int[][] x, int y){ 
    int[][] temp1 = new int[y][x[0].length]; 
    for(int i = 0; i < y; i++){ 
     for(int j = 0; j < x[0].length; j++) 
      temp1[i][j] = x[i][j]; 
    } 
    int[][] temp2 = new int[x.length-y][x[0].length]; 
    for(int i = y; i < x.length; i++){ 
     for(int j = 0; j < x[0].length; j++) 
      temp2[i][j] = x[i][j]; 
    } 
    int[][] temp1and2 = new int[temp1.length + temp2.length][x[0].length]; 
    System.arraycopy(temp1, 0, temp1and2, 0, temp1.length); 
    System.arraycopy(temp2, 0, temp1and2, temp1.length, temp2.length); 
    return temp1and2; 
} 

aber das hat nicht funktioniert. Ich erhalte den Fehler:

java.lang.ArrayIndexOutOfBoundsException: 2 auf dem temp2 [i] [j] = x [i] [j]; Linie. So zum Beispiel, TEMP1 und TEMP2 würde wäre beides sein:

1 2 3 
4 5 6 
7 8 9 

und das wäre kombiniert:

1 2 3 1 2 3 
4 5 6 4 5 6 
7 8 9 7 8 9 
+0

* "aber das hat nicht funktioniert." * Was genau bedeutet das? –

+1

Was ist 'x'? Ihr Code wird nicht kompiliert, bitte geben Sie ein überprüfbares Beispiel an. – Jack

+0

Ja, tut mir leid. Ich habe es nur mit der Fehlermeldung bearbeitet –

Antwort

0

Dies ist, wie ich es

//returns a new 2D array with temp1 stacked on top of temp2 or 
// null if the arrays aren't the correct dimensions 
public int[][] stackArrays(int[][] temp1, int[][] temp2) 
{ 
    int [][] temp1n2 = null; 

    if(temp1.length != 0 && temp1.length == temp2.length 
      && temp1[0].length == temp2[0].length) 
    { 
     //create the new array to hold both 
     temp1n2 = new int[temp1.length + temp2.length][temp1[0].length]; 

     for(int i = 0; i < temp1.length; i++) 
     { 
      for(int j = 0; j < temp1[i].length; j++) 
      { 
       temp1n2[i][j] = temp1[i][j]; 
       temp1n2[i + temp1.length][j] = temp2[i][j]; 
      } 
     } 

    } 
    return temp1n2; 
} 

von Hand tun würde Das Ergebnis von stackArrays (allZero2DArray, allOnes2DArray) ergibt das folgende 2D-Array:

000 
000 
000 
111 
111 
111