【问题标题】:How do I create an array using the for-each loop structure? [duplicate]如何使用 for-each 循环结构创建数组? [复制]
【发布时间】:2021-09-04 03:14:12
【问题描述】:

如何使用 for-each 循环结构创建一个包含用户输入的数组?

我通常会这样做:

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

我怎样才能做同样的事情,但使用 for-each 样式循环?

【问题讨论】:

  • 反问:我们为什么要使用foreach-loop?我们丢失了索引信息,显然我们需要访问特定的数组元素。
  • hi @AdrianMantilla - for (T curr : collection) - 当你已经收集了集合的内容时..

标签: java arrays loops foreach


【解决方案1】:

您需要一个包含索引值的循环。您可以使用IntStream.range(int, int) 生成有效索引并将其与forEach 结合使用。喜欢,

IntStream.range(0, array.length).forEach(i -> {
    System.out.println("Include a number into the array:");
    array[i] = sc.nextInt();
});

【讨论】:

    猜你喜欢
    • 2013-09-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 2011-12-06
    • 2012-12-24
    • 1970-01-01
    • 2011-05-12
    • 1970-01-01
    相关资源
    最近更新 更多