【问题标题】:How to create an array of numbers from (1 to x)?如何创建一个从(1到x)的数字数组?
【发布时间】:2021-10-27 00:29:32
【问题描述】:

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

尝试使用 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
        }


    }

}

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

【问题讨论】:

  • IntStream.rangeClosed(1, 25).map(i -> i * i * i).toArray()
  • 为什么要数组?在大多数情况下,Java 更喜欢其他方法(例如,列表或流)。

标签: java arrays integer


【解决方案1】:

您可以使用流 range 创建从 x 到 y 的范围,然后您可以使用 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]

【讨论】:

    【解决方案2】:

    如果我正确理解了这个问题,这可能会有所帮助。当您可以使用 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);
        }
    
      }
    

    【讨论】:

      猜你喜欢
      • 2018-08-09
      • 1970-01-01
      • 2021-07-20
      • 2023-02-01
      • 1970-01-01
      • 2023-03-19
      • 2022-01-09
      • 1970-01-01
      相关资源
      最近更新 更多