我有下面的代码,它应该通过将元素复制到一个新数组并每隔一个跳过来缩短数组。然而,我一直在获取一个空指针异常错误。
public void shorten()
{
// put your code here
if( samples.length % 2 == 0){
double [] temp = new double[samples.length / 2];
}
else if( samples.length % 2 != 0){
double [] temp = new double[samples.length / 2 - 1];
}
Arrays.fill(temp, 1.0);
int j = 0;
for(int i=0; i<= temp.length; i++){
temp[i] = samples[j];
j = j + 2;
}
samples = temp;
}
此代码的每个块:
if( samples.length % 2 == 0){
double [] temp = new double[samples.length / 2];
}
else if( samples.length % 2 != 0){
double [] temp = new double[samples.length / 2 - 1];
}
定义了一个只有1行作用域的temp
变量(为这些行隐藏temp
类变量(我想您已经有了(并保持不变(。
如果调用函数时temp
类变量是null
,那么在这些行之后它仍然是null
。相反,你需要这样的东西:
if( samples.length % 2 == 0){
temp = new double[samples.length / 2];
}
else { // samples.length % 2 != 0 is implied, since it's else
temp = new double[samples.length / 2 + 1]; // corrected -1 to +1
}
我在声明了一个新变量的temp
之前删除了double[]
。
此外,for循环检查需要是i < temp.length
,而不是<=
,因为在后一种情况下,它也将为i = temp.length
运行循环,从而尝试写入temp[temp.length]
,并且由于0索引,该索引超出了范围。
除了空指针,这里还有另一个错误。
i<= temp.length
应该是i< temp.length
。length
给出了总长度,因为元素计数从0开始,所以数组的最后一个元素是length-1
试试这个:我在需要的地方更改了您的代码。
public void shorten()
{
// put your code here
double [] temp=null; // here I declare temp Array
if( samples.length % 2 == 0){
temp = new double[samples.length / 2];
}
else if( samples.length % 2 != 0){
temp = new double[samples.length / 2 - 1];
}
Arrays.fill(temp, 1.0);
int j = 0;
for(int i=0; i< temp.length; i++){// here I removed "=" because Array index starts from 0 to length-1.
temp[i] = samples[j];
j = j + 2;
}
samples = temp;
}