Java Program to fill an array with random numbers

Java 8Object Oriented ProgrammingProgramming

Let us first crate an array −

double[] arr = new double[5];

Now, create Random class object −

Random randNum = new Random();

Now, fill the above array with random numbers −

for (int i = 0; i < 5; i++) {
arr[i] = randNum.nextInt();
}

Example

 Live Demo

import java.util.Arrays;
import java.util.Random;
public class Demo {
   public static void main(String args[]) {
      double[] arr = new double[5];
      Random randNum = new Random();
      for (int i = 0; i < 5; i++) {
         arr[i] = randNum.nextInt();
      }
      System.out.println("Random numbers = "+Arrays.toString(arr));
   }
}

Output

Random numbers = [-6.59888981E8, 1.141160731E9, -9.931249E8, 1.335266582E9, 8.27918412E8]
raja
Published on 25-Apr-2019 13:28:23
Advertisements