问题描述
我编写了以下代码,该代码接受数组的输入并将其拉伸后返回。
例如
{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]
如何解决此错误?
1楼
您正在重用引用原始数组中位置的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;
}
2楼
这段代码有一个很大的错误。
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;
}
}
希望您理解错误!!