如何使用for循环创建数组并分配线性值



我想创建一个数组,并使用for循环,我想以1o的增量赋值。到目前为止,这就是我所拥有的,但我没有得到我想要的结果。。。

public class ArrayDemo1 {
public static void main(String[] args) {
int array[] = new int[10];
System.out.println("The array elements are: ");
for (int i = 0; i <= array.length - 1; i++) { // Controls index...
for (int j = 0; j < 101; j += 10) { // Controls value of each array index...
array[i] = j;
System.out.println(array[i]);
}
}
}
}

这是我的输出[堆栈溢出不会让我有完整的输出,所以这是缩短的版本;这个输出(从/*开始,到*/结束(重复了10次。它从0到100打印了10次,增量为10]:

The array elements are:
/*
0
10
20
30
40
50
60
70
80
90
100
*/
Process finished with exit code 0

这是我想要的。对于每个索引,我想要一个值,下一个值应该是1o:的增量

The array elements are:
0
10
20
30
40
50
60
70
80
90

您不需要嵌套循环-值始终是索引乘以10:

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

编辑:
如果您不必使用循环,可以说使用流可以更优雅地完成这项工作

int[] array = IntStream.range(0, 10).map(i -> i * 10).toArray();

您不需要嵌套的for循环将值分配到单个数组中。

i*10填充每个索引,而不是引入j

您还应该在一个新的循环中打印数组,否则,保留数组并将其打印在的同一位置没有多大意义

而不是<= array.length - 1,你会想要< array.length

您也可以使用IntStream,这是实现相同结果的现代方法

最新更新