java 如何用连续数字填充数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28490869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:41:22  来源:igfitidea点击:

How do I fill an array with consecutive numbers

javaarraysinput

提问by Dan

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];

How do i fill this array with consecutive numbers starting from 1? All help is appreciated!!!

我如何用从 1 开始的连续数字填充这个数组?感谢所有帮助!!!

回答by Sotirios Delimanolis

Since Java 8

从 Java 8 开始

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

The rangeis in increments of 1. The javadoc is here.

以 1range为增量。javadoc 在这里

Or use rangeClosed

或使用 rangeClosed

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

回答by user253751

The simple way is:

简单的方法是:

int[] array = new int[NumOfValues];
for(int k = 0; k < array.length; k++)
    array[k] = k + 1;

回答by dave823

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

回答by brobee

One more thing. If I want to do the same with reverse:

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

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

I got the normal order again..

我又得到了正常的订单..

回答by Neverwork2123

You now have an empty array

你现在有一个空数组

So you need to iterate over each position (0 to size-1) placing the next number into the array.

因此,您需要遍历每个位置(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
}

回答by Dan

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]);

}