gpt4 book ai didi

java - 从 main 调用的数组

转载 作者:太空宇宙 更新时间:2023-11-04 06:39:40 24 4
gpt4 key购买 nike

我有以下代码,我想在 main 方法中调用 printArray 以便它可以打印。我不断收到以下错误:

cannot find symbol int[] arrays = new int[randomNumbers];

public static void main(String[] args) {
Scanner input = new Scanner(System.in);

System.out.print("How many random ints?");
int randomNumbers = input.nextInt();

System.out.print("What is the lower bound?");
int lower = input.nextInt();

System.out.print("What is the upper bound?");
int upper = input.nextInt();

int range = (upper - lower) + 1;
printArray(); //not working
}

public static void printArray(int[] array) {
int[] arrays = new int[randomNumbers];

for (int t = 0; t < array.length; t++) {
System.out.print("arr[" + t + "] :" + array[t]);
}

System.out.println();
}

非常感谢任何帮助。

最佳答案

如果我理解你的问题,请注释掉 printArray() 中的第一个声明

public static void printArray(int[] array) {
// int[] arrays = new int[randomNumbers];
for (int t = 0; t < array.length; t++) {
System.out.print("arr[" + t + "] :" + array[t]);
}
System.out.println();
}

但是,您可能应该使用 Arrays.toString(int[]) ,

System.out.println(Arrays.toString(array));

此外,在 main() 中,您需要将 int[] 传递给 printArray(),

Random rand = new Random();
int[] array = new int[randomNumbers];
for (int i = 0; i < array.length; i++) {
array[i] = lower + rand.nextInt(range);
}
printArray(array);

关于java - 从 main 调用的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24846624/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com