[英](Java) How to create an array with size based on user input, and also fill it with random numbers
这是学校作业的第一部分。 我不允许使用 ArrayList、Vector 或任何其他类似的 Java 类。
我应该让用户输入将生成多少个随机数,然后程序将创建一个包含该数量随机数的数组,并将这些数字打印出来。
我知道如何创建数组,以及如何将东西放入其中,但我一直在努力创建这种特定类型的数组。 我知道我无法创建一个数组,然后在它已经存在后更改它的大小。
感谢任何关于如何实现这一点的提示或明确的解释,因为我已经坐了 3 天了,不知道如何继续。
我不想给你一切,但我给了你很多。 我希望这能帮助你理解,你现在需要的只是看看如何生成随机数。
//This segment of code will take a number as input
Scanner input = new Scanner(System.in);
int num = input.nextInt();
//this will initialize the array
int[] arr = new int[num];
//this will let you initialize every element in array
for(int i = 0; i < arr.length; i++){
{randomized number code}
}
Scanner scan = new Scanner(System.in);
System.out.print("Enter array length: ");
int[] arr = new int[in.nextInt()];
Random random = new Random();
for(int i = 0; i < arr.length; i++)
arr[i] = random.nextInt(100); // random from 0 to 99 inclusive
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.