[英](Java) How to create an array with size based on user input, and also fill it with random numbers
This is the first part of aa school assignment.这是学校作业的第一部分。 I am not allowed to use ArrayList, Vector, or any other similar Java-class.我不允许使用 ArrayList、Vector 或任何其他类似的 Java 类。
I'm supposed to have a user input how many random numbers will be generated, and then the program shall create an array with that amount of random numbers in it, and print those numbers out.我应该让用户输入将生成多少个随机数,然后程序将创建一个包含该数量随机数的数组,并将这些数字打印出来。
I know how to create arrays, and how to put things into them, but I've been hitting my head against the wall of creating this specific kind of array.我知道如何创建数组,以及如何将东西放入其中,但我一直在努力创建这种特定类型的数组。 I know I can't create an array and then change the size of it once it already exists.我知道我无法创建一个数组,然后在它已经存在后更改它的大小。
Grateful for any kind of hints or flat out explanations on how to accomplish this, as I've been sitting with this for 3 days now with no idea of how to proceed.感谢任何关于如何实现这一点的提示或明确的解释,因为我已经坐了 3 天了,不知道如何继续。
I didn't want to give you EVERYTHING, but I gave you alot.我不想给你一切,但我给了你很多。 I hope this helps you understand, all you need now is to look at how to generate random numbers.我希望这能帮助你理解,你现在需要的只是看看如何生成随机数。
//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.