首页 > 解决方案 > 如何创建一个从(1到x)的数字数组?

问题描述

在 JDK 16 上运行。最初试图弄清楚如何像range(1,x+1)在 python 中那样创建一个数字数组。

尝试使用 VSC 中的内置帮助无济于事,然后切换到 IntelliJ,如果没有 VSC 的智能感知,这让我更加困惑。在谷歌搜索了两个小时,尝试了类似instream然后转换为数组的东西,但失败了。尝试对 int[] 进行类型转换,但这也不起作用。即使使用 W3Schools 的智能意识并在这里搜索一个小时也无法弄清楚..

问题:我想创建一个从 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
        }


    }

}

这只是我对代码的最新尝试,在重写了一堆并且没有运气之后..

标签: javaarraysinteger

解决方案


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

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]

推荐阅读