Create two Integer
ArrayLists
containing n elements each where n will be taken from the user.
so basically if a user inputs '6' two arrays with 6 elements needs to be created. How would I do this?
This is what I have.. but its not even remotely correct.
Scanner input= new Scanner(System.in);
System.out.println("please enter a integer 'n' ");
int x= input.nextInt();
int[] a = { 1, 4, 9, 16 };
int[] b = { 9, 7, 4, 9, 11 };
In order to generate random array of integers in Java, we use the nextInt() method of the java. util. Random class. This returns the next random integer value from this random number generator sequence.
To get a random number, we use the rand() method. When invoked, the rand() function in C++ generates a pseudo-random number between 0 and RAND MAX. Whenever this method is used, it utilizes an algorithm that gives a succession of random numbers.
If you want to generate random integer array from an interval, here are the options
// generate 100 random number between 0 to 100
int[] randomIntsArray = IntStream.generate(() -> new Random().nextInt(100)).limit(100).toArray();
//generate 100 random number between 100 to 200
int[] randomIntsArray = IntStream.generate(() -> new Random().nextInt(100) + 100).limit(100).toArray();
You can take input from the user by using a scanner like this -
Scanner input= new Scanner(System.in);
System.out.println("Enter the array size: ");
int n = input.nextInt();
Now create a function generateRandomArray(int n)
like this -
public List<Integer> generateRandomArray(int n){
ArrayList<Integer> list = new ArrayList<Integer>(n);
Random random = new Random();
for (int i = 0; i < n; i++)
{
list.add(random.nextInt(1000));
}
return list;
}
Here - random.nextInt(1000)
will generate a random number from the range 0 to 1000. You can fix the range as you want.
Now you can call the function with the value n
get from the user -
ArrayList<Integer> list1 = generateRandomArray(n);
ArrayList<Integer> list2 = generateRandomArray(n);
Hope it will help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With