如何用连续的数字填充一个数组

15

我想使用连续的整数填充一个数组。我已经创建了一个包含用户输入数量索引的数组:

Scanner in = new Scanner(System.in);
int numOfValues = in.nextInt();

int [] array = new int[numOfValues];

我该如何用连续的数字从1开始填充这个数组呢?非常感谢任何帮助!!!


请使用适当的命名规范。将其命名为 numOfValues。类以大写字母开头,而不是变量。 - Ascalonian
6个回答

43

自Java 8以来

//                               v end, exclusive
int[] array = IntStream.range(1, numOfValues + 1).toArray();
//                            ^ start, inclusive

range 增量为 1。 javadoc 在这里

或者使用rangeClosed

//                                     v end, inclusive
int[] array = IntStream.rangeClosed(1, numOfValues).toArray();
//                                  ^ start, inclusive

4
简单的方法是:
int[] array = new int[NumOfValues];
for(int k = 0; k < array.length; k++)
    array[k] = k + 1;

2
for(int i=0; i<array.length; i++)
{
    array[i] = i+1;
}

0

你现在有一个空数组

所以你需要迭代每个位置(从0到size-1),将下一个数字放入数组中。

for(int x=0; x<NumOfValues; x++){ // this will iterate over each position
     array[x] = x+1; // this will put each integer value into the array starting with 1
}

0

还有一件事。如果我想反过来做同样的事情:

int[] array = new int[5];
        for(int i = 5; i>0;i--) {
            array[i-1]= i;
        }
        System.out.println(Arrays.toString(array));
}

我再次得到了正常的顺序...


你又得到了正常订单.. - 那么?我们能做什么呢? - Enamul Hassan

-2
Scanner in = new Scanner(System.in);
int numOfValues = in.nextInt();

int[] array = new int[numOfValues];

int add = 0;

for (int i = 0; i < array.length; i++) {

    array[i] = 1 + add;

    add++;

    System.out.println(array[i]);

}

虽然这段代码可能回答了问题,但提供关于它是如何解决问题的额外上下文会提高答案的长期价值。 - Michael Parker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接