如何用连续数字填充数组 [英] How do I fill an array with consecutive numbers
本文介绍了如何用连续数字填充数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用连续的整数填充数组.我创建了一个数组,其中包含与用户输入一样多的索引:
I would like to fill an array using consecutive integers. I have created an array that contains as much indexes as the user enters:
Scanner in = new Scanner(System.in);
int numOfValues = in.nextInt();
int [] array = new int[numOfValues];
如何用从1开始的连续数字填充此数组? 感谢所有帮助!
How do i fill this array with consecutive numbers starting from 1? All help is appreciated!!!
推荐答案
自Java 8起
// v end, exclusive
int[] array = IntStream.range(1, numOfValues + 1).toArray();
// ^ start, inclusive
The range
is in increments of 1. The javadoc is here.
或使用 rangeClosed
// v end, inclusive
int[] array = IntStream.rangeClosed(1, numOfValues).toArray();
// ^ start, inclusive
这篇关于如何用连续数字填充数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文