Given String[] [] arr2D = [["sun", "moon"], null, ["black", "white"], ["dog", "cat"], null], how can I loop through arr2D to shift the first null to the immediate right of ["dog", "cat"] or to the end of the array so that arr2D becomes [["sun", "moon"], ["black", "white"], ["dog", "cat"], null, null]?
I have tried adapting this example involving 1D arrays but I ended up with a nullPointerException every time.
// I'm hardcoding i < 4 because there are 4 elements between and including ["sun", "moon"] and ["dog", "cat"]
for(int i = 0; i < 4; i++) {
if(arr2D[i] == null) {
for(int j = i + 1; j < 4; j++) {
arr2D[j - 1][0] = arr2D[j][0];
arr2D[j- 1][1] = arr2D[j][1];
}
arr2D[4 - 1] = null;
break;
}
}
Exception in thread "main" java.lang.NullPointerException: Cannot store to object array because "items[...]" is null