在Java中使用for循环填充int数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23372292/
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
Populate int array with for loop in Java
提问by user2457459
I have an array named numbers that I want to populate with a for loop:
我有一个名为 numbers 的数组,我想用 for 循环填充它:
int[] numbers;
for ( int i = 0; i <=10; i++)
{
// want to populate the array with a sequence of 0-10
}
How can I populate the 11 values generated from the above for loop into my array?
如何将上述 for 循环生成的 11 个值填充到我的数组中?
采纳答案by ggovan
First you need to define what numbers
is, you have only declared it.
首先你需要定义是什么numbers
,你只是声明了它。
int[] numbers = new int[11];
Then insert the values you want.
然后插入你想要的值。
for ( int i = 0; i <=10; i++)
{
numbers[i] = i;
}
回答by Jake Toronto
If you are using Java 7 or lower, do this:
如果您使用的是Java 7 或更低版本,请执行以下操作:
int[] numbers = new int[11];
for ( int i = 0; i <=10; i++)
{
numbers[i] = i;
}
For Java 8, there is a more concise way to do this:
对于Java 8,有一种更简洁的方法来做到这一点:
int[] numbers = IntStream.rangeClosed(0, 10).toArray()