问题
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.
回答1:
When you say this line
int[][] rev = new int[a.length][];
You have created an array of length a.length
of arrays, but the internal arrays are all null
. So you are getting a NullPointerException
on this line:
rev[row-1][col-1]= a[x][y];
You need to create your internal arrays inside the first for loop. This will satisfy your "jagged array" requirement.
for(int x=0;x<a.length;x++){
int col = a[x].length-1;
rev[row-1] = new int[a[x].length]; // Add this to create differing lengths.
for(int y=0; y< a[x].length;y++){
回答2:
Your array rev
has not been initialized in its second coordinate. After your declaration int[][] rev = new int[a.length][]
, all your rev[i]
are null
objects (arrays are objects, even for primitive types). To avoid that, initialize with int[][] rev = new int[a.length][a[0].length]
or with rev[i] = new int[a[i].length]
or so, if the array is jagged.
来源:https://stackoverflow.com/questions/15580370/i-am-trying-to-reverse-a-two-dimensional-array-and-keep-getting-a-null-exception