-2

How would you create an array with user input using the for-each loop structure?

I would normally do:

for (int i = 0; i < array.length; i++) {
    System.out.println("Include a number into the array:");
    array[i] = sc.nextInt();
}

How can I do the same thing but using a for-each style loop?

adrman47
  • 49
  • 3
  • Counter-question: why should we use a `foreach`-loop? We loose the index-information, which we clearly need to access the specific array-element. – Turing85 Jun 19 '21 at 22:17
  • hi @AdrianMantilla - for (T curr : collection) - is for when you have already gathered the contents of the collection .. – Mr R Jun 19 '21 at 22:18

1 Answers1

0

You need a loop with the values of the indices. You could use an IntStream.range(int, int) to generate the valid indices and combine that with a forEach. Like,

IntStream.range(0, array.length).forEach(i -> {
    System.out.println("Include a number into the array:");
    array[i] = sc.nextInt();
});
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249