简体   繁体   English

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

[英]How can I use a for loop to create an array and assign linear values?

I want to create an array and using a for loop and I want to assign values with an increment of 1o.我想创建一个数组并使用 for 循环,我想以 1o 的增量分配值。 So far here is what I have and I am not getting the result I want...到目前为止,这就是我所拥有的,但我没有得到我想要的结果......

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

            }
        }

    }

}

Here is my output [Stack overflow won't let me have the whole output so here is the shortened version;这是我的 output [堆栈溢出不会让我拥有整个 output 所以这是缩短的版本; This output (starting at /* and ending at */) was repeated 10 full times.这个 output(从 /* 开始到 */ 结束)重复了 10 次。 It printed from 0 to 100 ten times with an increment of 10]:它以 10 为增量从 0 到 100 打印十次]:

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

Here is what I want.这就是我想要的。 For every index, I want one value and the next value should be an increment of 1o:对于每个索引,我想要一个值,下一个值应该是 1o 的增量:

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

You don't need a nested for loop to assign values into a single array.您不需要嵌套的 for 循环将值分配给单个数组。

Populate each index by i*10 rather than introduce j .i*10填充每个索引,而不是引入j

You should also print the array in a new loop, otherwise, there's not much purpose for keeping the array and printing it in the same location您还应该在新循环中打印数组,否则,将数组保留并打印在同一位置没有太大意义

And rather than <= array.length - 1 , you'll want < array.length而不是<= array.length - 1 ,你会想要< array.length

You can also use an IntStream , which is the modern way to achieve the same result您还可以使用IntStream ,这是实现相同结果的现代方式

You don't need a nested loop - the value is always the index multiplied by 10:您不需要嵌套循环 - 值始终是索引乘以 10:

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

EDIT:编辑:
If you don't have to use loops, this could arguably be done more elegantly with a stream:如果您不必使用循环,则可以使用 stream 更优雅地完成此操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM