-1

I'm trying to copy a 2d array and then print the copy. When I try to run my code NullPointerExeption pops up. The exact thing it says is:

Exception in thread "main" java.lang.NullPointerException
    at CharacterArray2DCopier.kopioi2dTaulukko(CharacterArray2DCopier.java:12)
    at CharacterArray2DCopier.main(CharacterArray2DCopier.java:33))

I can't use the .array things (I don't know what they're called). Here's the code:

`
public class CharacterArray2DCopier {
public static char [][] copy2dArray(char[][] array){
if (array!= null && array.length > 0){
    char[][] array2 =  new char[array.length-1][];
    for (int ind = 0; ind < array.length; ind++){
        for (int und = 0; und < array[ind].length; und++) {
            array2[ind][und] = array[ind][und];
        }
    }
    return array2;
}
else {
    return null;
}
}
public static void print2d(char[][] array){
    if (array != null) {
        for (int ind = 0; ind < array.length; ind++){
            for (int und = 0; und < array[ind].length; und++) {
                System.out.print(array[ind][und]);
            }
            System.out.println();
        }
    }
}
public static void main (String[] args){
    char[][] array = {{ '+', '-', '+', '.' }, { '.', '.', '+', '-'}};
    char[][] array2 = copy2dArray(array);
    print2d(array2);
}
}`

i've also tried this:

`...
public static char [][] copy2dArray(char[][] array){
    if (array!= null && array.length > 0){
        char[][] array2 =  new char[array.length-1][array[array.length-1][array[array.length-2].length-2]];
        for (int ind = 0; ind < array.length; ind++){
            for (int und = 0; und < array[ind].length; und++) {
                array2[ind][und] = array[ind][und];
            }
        }
    return array2;
    }
    else {
        return null;
    }
    ...
`

but then it says:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1 
    at CharacterArray2DCopier.kopioi2dTaulukko(CharacterArray2DCopier.java:12) 
    at CharacterArray2DCopier.main(CharacterArray2DCopier.java:33)

What do i do? Sorry if this written wrong or it's a dumb question, I'm new to all this.

Samkayoki
  • 59
  • 5

1 Answers1

0

A 2D array is just an array of arrays -- and arrays, as you know, need to be instantiated.

You do that with the "outer" array, but not the inner ones -- the ones you access via array2[ind]. You need to create those, right after the for (int ind = 0 line.

yshavit
  • 42,327
  • 7
  • 87
  • 124