如何创建从(1 到 x)的数字数组?

How to create an array of numbers from (1 to x)?

运行 on JDK 16. 最初试图弄清楚如何在 python.

中创建像 range(1,x+1) 这样的数字数组

尝试使用 VSC 中的内置帮助无济于事,然后切换到 IntelliJ,这让我在没有 VSC 智能感知的情况下更加困惑。连续搜索 google 两个小时尝试 instream 之类的东西,然后转换为数组,但失败了。尝试将类型转换为 int[] 但这也不起作用。凭着W3School的灵敏在这里找了一个小时也没搞明白..

问题: 我想创建一个从 1 到 x 的数组。假设 x 等于 25。 然后,我想在 for 循环中一个一个地遍历它们。 在四循环内,我想将它乘以三并构建一个具有 'x' 槽的动态数组。 (因此,在本例中为 25。)

这是我到目前为止尝试过的方法:

import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class cubeNums {
    public static void someVoidMethod() {
        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter x: ");
        // take in x val
        int x = scan.nextInt();
        // create int[] array to iterate thru for loop
        list numList = (IntStream.range(-2, 10)).boxed().collect(Collectors.toList());


        for (int[] numArray = new int[15]) {
              //incomplete
        }


    }

}

这只是我对代码的最新尝试,在重写了一堆代码却没有成功之后..

如果我正确理解问题,这可能会有所帮助。当您可以使用 for 循环时,您不想过于复杂。

public static void someVoidMethod() {
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter x: ");
    // take in x val
    int x = scan.nextInt();

    List<Long> calculatedList = new ArrayList<>();
    for (int i = 1; i <= x; i++) {
      calculatedList.add((long) Math.pow(i, 3));
    }

    for (Long number : calculatedList) {
      System.out.println(number);
    }

  }

您可以使用流 range 创建从 x 到 y 的范围,然后您可以用 map 替换生成的值,并使用 toArray[=18 将这些值放入数组=]

public static void main(String[] args) {
    int[] arr = IntStream.range(1, 25).map(x -> (int) Math.pow(x, 3)).toArray();
    System.out.println(Arrays.toString(arr));
}

如果你想得到一个列表,你首先需要用boxed框住数字并调用collect

List<Integer> list = IntStream
        .range(1, 25)
        .map(x -> (int) Math.pow(x, 3))
        .boxed()
        .collect(Collectors.toList());

System.out.println(list);

输出

[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000, 1331, 1728, 2197, 2744, 3375, 4096, 4913, 5832, 6859, 8000, 9261, 10648, 12167, 13824]