Generate array of random numbers


 

Generate array of random numbers

In this section, you will learn how to accept 10 numbers and display 5 numbers from them randomly.

In this section, you will learn how to accept 10 numbers and display 5 numbers from them randomly.

Generate array of random numbers

You can generate a random number either by using the Random class or by using the static method Math.random() but it is better to use Random class. If you want to generate a series of random numbers then there is no need to create a new Random object for each new random number. In this section, we are going to accept 10 numbers and display 5 numbers from them randomly.

Here is the code:

import java.util.*;

class RandomNumberExample {
	static Random generator = new Random();

	public static int get(int[] array) {
		int rnd = generator.nextInt(array.length);
		return array[rnd];
	}

	public static void main(String[] args) {
		int arr[] = new int[10];
		Scanner input = new Scanner(System.in);
		System.out.println("Enter 10 numbers: ");
		for (int i = 0; i < 10; i++) {
			arr[i] = input.nextInt();
		}
		System.out.println();
		System.out.println("Random numbers are: ");
		int random[] = new int[5];
		for (int i = 0; i < random.length; i++) {
			random[i] = RandomNumberExample.get(arr);
			System.out.println(random[i]);
		}
	}
}

Output:

Enter 10 numbers:
1
2
3
4
5
6
7
8
9
10

Random Numbers are:
4
8
6
2
9

Ads