我试图弄清楚如何从数组中删除中间的元素(如果它的长度为偶数)以及中间元素(如果数组的长度为奇数)。程序在编译时运行,但是结果没有变化。我也不确定我是否正确使用System.arraycopy方法(第一个位置是原始数组,第二个是您要开始复制的位置,第三个是目标数组,第四个是目标数组的起始位置,最后一个位置是要复制的数组元素的数量)这是我到目前为止的代码:
public void removeMiddle(int[] values)
{
//lets say the array size is 10
boolean even = (values.length % 2 == 0);
int middle1 = values.length/2;
int middle2 = values.length/2 - 1;
if(even)
{
int[] copy = new int[values.length - 2];
//copying the elements 0-3 to the new array
System.arraycopy(values, 0, copy, 0, copy.length - middle1 -1);
//copying the last 4 elements to the new array
System.arraycopy(values, middle1 + 1,copy, middle1, copy.length-middle2 - 1);
}
else if(!even)
{
int[] copy = new int[values.length - 1];
//copying elements 0-3
System.arraycopy(copy,0,copy, 0, copy.length - middle1 -1);
System.arraycopy(copy,middle1 +1 ,copy, middle1 + 1, copy.length - middle1 -1 );
}
}
最佳答案
复制后一半时索引错误,数组索引从0开始。
public void removeMiddle(int[] values)
{
//lets say the array size is 10
boolean even = (values.length % 2 == 0);
int middle1 = values.length/2;
int middle2 = values.length/2 - 1;
if(even)
{
int[] copy = new int[values.length - 2];
//copying the elements 0-3 to the new array
System.arraycopy(values, 0, copy, 0, copy.length - middle1 -1);
//copying the last 4 elements to the new array
System.arraycopy(values, middle1, copy, middle2, copy.length-middle1 - 1);
}
else
{
int[] copy = new int[values.length - 1];
//copying elements 0-3
System.arraycopy(copy, 0, copy, 0, copy.length - middle1 -1);
System.arraycopy(copy, middle1 ,copy, middle1 , copy.length - middle1 -1 );
}
}