How to find the index of an item in an array, which is currently being iterated through

Viewed 39

So, I am creating an iteration of an object for every element in two different arrays, but one of the parameters of the object is the index of one of the arrays.

I have the first array, array1, from which I need the value at the current index. However for array2, the object requires both the value at the given index, and the int value of the index itself, but I'm not sure how to access it.

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);
    }
  }
}
1 Answers

The answer is as simple as putting the number which you are iterating through. In the given example this would be x.

Astronaut astro = new Astronaut(array1[i], array2[x], result, x); the reason for this is because x will be increased with every iteration of the loop, meaning it will be the same as the index.

Related