问题描述
这里是我的方法,它想反转数组.(此外,请记住,此方法可以接收锯齿状数组)
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
我不断得到
Exception in thread "main" java.lang.NullPointerException
at Home.reverse(Home.java:259)
at Home.main(Home.java:56)
Java结果: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.
推荐答案
说这句话
int[][] rev = new int[a.length][];
您已经创建了一个长度为 a.length
个数组的数组,但是内部数组都是 null
.因此,您在此行上收到 NullPointerException
:
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];
您需要在第一个for循环内创建内部数组.这将满足您的锯齿状阵列"要求.
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++){
这篇关于我正在尝试反转二维数组,并不断收到null异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!