Here is my method that is suppose to reverse the array. (Also, keep in mind that this method can receive a jagged array)
public static int[][] reverse(int[][]a){
int[][] rev = new int[a.length][];
int row = a.length;
for(int x=0;x<a.length;x++){
int col = a[x].length-1;
for(int y=0; y< a[x].length;y++){
rev[row-1][col-1]= a[x][y];
col--;
}
row--;
}
return rev;
}// reverse method
I keep getting
Exception in thread "main" java.lang.NullPointerException
at Home.reverse(Home.java:259)
at Home.main(Home.java:56)
Java Result: 1
Here is my main that calls that method
int[][] two = {{1,2,3,4},{0,1,2},{9},{1,3,5,7}};
System.out.println("The size of array os " + ar.length);
System.out.println("The columns of array is " + ar[0].length);
int[][] rev;
//int[] b = concatenate(ar);
//int[] c = concatenate(two);
//int[][] rev = reverse(ar);
//for(int x=0;x<c.length;x++){System.out.println("worked" + c[x]);}
rev = reverse(two);
//for(int x = 0;x<rev.length;x++){
// for(int y = 0;y<rev[x].length;y++){
// System.out.print(rev[x][y]);
//}
//}
for(int x=0;x<rev.length;x++){
for(int y=0;y<rev[x].length;y++){
System.out.print(rev[x][y]);
}
}
}// main
So my question is really, where did I go wrong? I traced my reverse method and it looks like it should be doing its job but apparently not.
When you say this line
You have created an array of length
a.length
of arrays, but the internal arrays are allnull
. So you are getting aNullPointerException
on this line:You need to create your internal arrays inside the first for loop. This will satisfy your "jagged array" requirement.
Your array
rev
has not been initialized in its second coordinate. After your declarationint[][] rev = new int[a.length][]
, all yourrev[i]
arenull
objects (arrays are objects, even for primitive types). To avoid that, initialize withint[][] rev = new int[a.length][a[0].length]
or withrev[i] = new int[a[i].length]
or so, if the array is jagged.