【问题标题】:How to find the index of an item in an array, which is currently being iterated through如何在当前正在迭代的数组中查找项的索引
【发布时间】:2021-04-19 16:37:08
【问题描述】:

所以,我正在为两个不同数组中的每个元素创建一个对象的迭代,但对象的参数之一是其中一个数组的索引。

我有第一个数组,array1,我需要当前索引处的值。但是对于array2,该对象既需要给定索引处的值,也需要索引本身的int值,但我不确定如何访问它。

public void method() {
  for (int i = 0; i < array1.length; i++) {
    for (int x = 0; x < array2.length; x++) {
      int result = random.nextInt(highNumber - lowNumber) + lowNumber;
      Astronaut astro = new Astronaut(array1[i], array2[x], result, array2index);
    }
  }
}

【问题讨论】:

    标签: java arrays indexing


    【解决方案1】:

    答案很简单,只需输入您正在迭代的数字即可。在给定的示例中,这将是 x

    Astronaut astro = new Astronaut(array1[i], array2[x], result, x); 这样做的原因是因为x 会随着循环的每次迭代而增加,这意味着它将与索引相同。

    【讨论】:

      猜你喜欢
      • 2014-09-12
      • 2021-11-12
      • 2018-11-19
      • 2021-01-29
      • 2013-12-18
      • 1970-01-01
      • 1970-01-01
      • 2020-11-15
      • 1970-01-01
      相关资源
      最近更新 更多