How to Add Random Number to an Array in Java?
Last Updated :
12 Feb, 2024
To an array of integers with random values the nextInt() method from the java.util.Random class is used. From the random number generator sequence, this method returns the next random integer value.
Assign a Random Value to an Array
We can assign random values to an array by two approaches. If we do not pass any arguments to the nextInt() method, then it will assign some arbitrary random value of integers range in Java and if we pass some argument to the nextInt() method then it will generate numbers in the range between 0 to the argument passed.
Example 1:
In this, we assign random values to an array without any range or ranging between the minimum value of integers to the maximum value of integers (i.e. not passing arguments).
Java
import java.util.Random;
import java.util.*;
public class RandomArrayValues {
public static void main(String[] args) {
int n = 5 ;
int [] randomArray = new int [n];
Random random = new Random();
for ( int i = 0 ; i < n; i++) {
randomArray[i] = random.nextInt();
}
System.out.println( "Random assigned value of Array are: " );
for ( int value : randomArray) {
System.out.print(value+ " " );
}
}
}
|
Output
Random assigned value of Array are:
-170019732 2032213863 -1596767761 -1668938134 -210148393
Example 2:
In this, we are assigning random values to array with some specific range (i.e. passing arguments)
Java
import java.util.Random;
import java.util.*;
public class RandomArrayValues {
public static void main(String[] args) {
int n = 5 ;
int [] randomArray = new int [n];
Random random = new Random();
for ( int i = 0 ; i < n; i++) {
randomArray[i] = random.nextInt( 100 );
}
System.out.println( "Random assigned value of Array are: " );
for ( int value : randomArray) {
System.out.print(value+ " " );
}
}
}
|
Output
Random assigned value of Array are:
4 51 85 25 33
Share your thoughts in the comments
Please Login to comment...