我编写了以下代码,它接受数组的输入并返回拉伸的数组。
例如
{18, 7, 9, 90}应以下列方式退回:
{9, 9, 4, 3, 5, 4, 45, 45}这就是我写的代码:
import java.util.Arrays;
public class Stretching
{
public static void main(String[] args)
{
int[] list = {18, 7, 9, 90};
int[] list2 = stretch(list);
System.out.println(Arrays.toString(list));
System.out.println(Arrays.toString(list2));
}
public static int[] stretch(int[] array)
{
int[] stretched = new int[2*array.length];
for (int i = 0; i < array.length; i++)
{
if (array[i]%2 == 1)
{
stretched[i] = array[i]/2;
stretched[i] = array[i]/2 + 1;
}
else
{
stretched[i] = array[i]/2;
stretched[i] = array[i]/2;
}
}
return stretched;
}
}不幸的是,输出如下:
[9, 3, 4, 45, 0, 0, 0, 0]如何纠正此错误?
发布于 2015-07-26 16:42:03
您正在重用引用原始数组中位置的i索引。相反,由于您正在拉伸数组,目标索引应该是:
if (array[i]%2 == 1)
{
stretched[2 * i] = array[i]/2 + 1;
stretched[2 * i + 1] = array[i]/2;
}
else
{
stretched[2 * i] = array[i]/2;
stretched[2 * i + 1] = array[i]/2;
}发布于 2015-07-26 16:44:46
这段代码有一个很大的错误。
if (array[i]%2 == 1)
{
// Here array[i]/2+1 to index i
stretched[i] = array[i]/2 + 1;
// Here array[i]/2 to index i
stretched[i] = array[i]/2;
}
else
{
// Here array[i]/2 to index i
stretched[i] = array[i]/2;
// Here array[i]/2 to index i
stretched[i] = array[i]/2;
}在这里,您要在同一个索引上为拉伸的数组分配两个值,您真正想要的是将它们分配给连续的索引。
相反,您必须修改代码,如下所示
import java.util.Arrays;
class Stretching
{
public static void main(String[] args)
{
int[] list = {18, 7, 9, 90};
int[] list2 = stretch(list);
System.out.println(Arrays.toString(list));
System.out.println(Arrays.toString(list2));
}
public static int[] stretch(int[] array)
{
int[] stretched = new int[2*array.length];
for (int i = 0; i < array.length; i++)
{
if (array[i]%2 == 1)
{
stretched[2 * i] = array[i]/2 + 1;
stretched[2 * i + 1] = array[i]/2;
}
else
{
stretched[2 * i] = array[i]/2;
stretched[2 * i + 1] = array[i]/2;
}
}
return stretched;
}
}希望你能理解窃听器!!
https://stackoverflow.com/questions/31639383
复制相似问题