【问题标题】:How to fix extra zeroes being returned如何修复返回的额外零
【发布时间】:2019-11-04 22:05:24
【问题描述】:

我正在尝试将一个数组复制到一个新数组中,然后返回该新数组。问题是我只需要从某个范围内复制数组。

我做了一个 for 语句,将 int i 分配给决定开始的参数,并将其设置为运行,直到到达决定结束的参数。

int[] newSound = new int[sound.length];

for (int i = start_index; i < end_index; ++i) {
    newSound[i] = sound[i];
}
return newSound;

如果数组是 [3, 2, 5, 6, 9] 并且范围是 [1, 3],它只会返回 [2, 5, 6]。问题是当我运行我的程序时,它返回 [0, 2, 5, 6, 0]。有谁知道为什么会这样?

【问题讨论】:

  • 为什么不使用Arrays.copyOfRange()
  • 如果你想要一个更小的数组,你不需要让它和原来的大小一样。
  • 如果你已经有了目标数组,也可以使用System.arrayCopy()
  • 您是否打算将您的end_index 包含在最终数组中?您发布的代码不会这样做,这是我的答案基于

标签: java arrays copy


【解决方案1】:

通过将数组创建为复制范围的大小(start_indexend_index)来修复:

int[] newSound = new int[end_index - start_index];

您的循环现在应该是:

for (int i = start_index; i < end_index; ++i) {
    newSound[i - start_index] = sound[i];
}

正如 cmets 中所建议的,Arrays.copyOfRange 是上述方法的更好替代方案,因为它可以处理超出范围的索引和负范围。

像这样使用它:

int[] newSound = Arrays.copyOfRange(sound, start_index, end_index);

【讨论】:

  • 非常感谢您解决了这个问题。但是,我仍然对为什么 for 循环需要 newSound[i​​ - start_index] 而不仅仅是 newSound[I] 感到困惑。
  • @Spiriteater 因为i 可能不会从零开始。所以从每个i 中减去start_index 以保证我们从零开始,然后是12
【解决方案2】:

您的目标数组长度为 5,并且您正在复制到与源相同的位置。

你想这样做,我相信:

int[] newSound = new int[end_index - start_index + 1];
for (int i = start_index; i <= end_index; ++i) {
  newSound[i - start_index] = sound[i];
}
return newSound;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 2020-12-07
    • 2013-08-01
    • 2019-09-02
    • 2016-01-06
    • 1970-01-01
    • 2021-10-11
    相关资源
    最近更新 更多