我编写了以下代码,它接受数组的输入 并将它拉伸。
例如
{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]
如何解决此错误?
答案 0 :(得分:3)
您正在重用引用原始数组中位置的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;
}
答案 1 :(得分:1)
此代码中存在一个非常大的错误。
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;
}
}
希望你能理解这个错误!!