[java] Fill an array with random numbers

I need to create an array using a constructor, add a method to print the array as a sequence and a method to fill the array with random numbers of the type double.

Here's what I've done so far:

import java.util.Random;

public class NumberList {
    private static double[] anArray;

    public static double[] list() {
        return new double[10];
    }
    
    public static void print(){
        System.out.println(String.join(" ", anArray);
    }

    public static double randomFill() {
        return (new Random()).nextInt();
    }
    
    public static void main(String args[]) {
        // TODO
    }
}

I'm struggling to figure out how to fill the array with the random numbers I have generated in the randomFill method. Thanks!

This question is related to java arrays

The answer is


You could loop through the array and in each iteration call the randomFill method. Check it out:

import java.util.Random;

public class NumberList {
    private static double[] anArray;

    public static double[] list() {  
        return new double[10];
    }

    public static void print() {
        System.out.println(String.join(" ", anArray));
    }


    public static double randomFill() {
        return (new Random()).nextInt();
    }

    public static void main(String args[]) {
        list();
        for(int i = 0; i < anArray.length; i++)
            anArray[i] = randomFill();

        print();
    }
}

I tried to make this as simple as possible in Java. This makes an integer array of 100 variables and fill it with integers between 0 and 10 using only three lines of code. You can easily change the bounds of the random number too!

int RandNumbers[]=new int[100];
for (int i=0;i<RandNumbers.length;i++)
    RandNumbers[i]=ThreadLocalRandom.current().nextInt(0,10);

This will give you an array with 50 random numbers and display the smallest number in the array. I did it for an assignment in my programming class.

public static void main(String args[]) {
    // TODO Auto-generated method stub

    int i;
    int[] array = new int[50];
    for(i = 0; i <  array.length; i++) {
        array[i] = (int)(Math.random() * 100);
        System.out.print(array[i] + "  ");

        int smallest = array[0];

        for (i=1; i<array.length; i++)
        {
        if (array[i]<smallest)
        smallest = array[i];
        }



    }

}

}`


Fast and Easy

double[] anArray = new Random().doubles(10).toArray();

Try this:

public void double randomFill() {
    Random rand = new Random();
    for (int i = 0; i < this.anArray.length(); i++)
        this.anArray[i] = rand.nextInt();
}

People don't see the nice cool Stream producers all over the Java libs.

public static double[] list(){
    return new Random().ints().asDoubleStream().toArray();
}

You can call the randomFill() method in a loop and fill your array in the main() method like this.

public static void main(String args[]) {
    for (int i = 0; i < anArray.length; i++) {
        anArray[i] = randomFill();
    }
}

You would then need to use rand.nextDouble() in your randomFill() method the array to be filled is a double array. The below snippet should help you get random double values to be filled into your array.

double randomDoubleValue = rand.nextDouble();
return randomDoubleValue;

This seems a little bit like homework. So I'll give you some hints. The good news is that you're almost there! You've done most of the hard work already!

  • Think about a construct that can help you iterate over the array. Is there some sort of construct (a loop perhaps?) that you can use to iterate over each location in the array?
  • Within this construct, for each iteration of the loop, you will assign the value returned by randomFill() to the current location of the array.

Note: Your array is double, but you are returning ints from randomFill. So there's something you need to fix there.


If the randomness is controlled like this there can always generate any number of data points of a given range. If the random method in java is only used, we cannot guarantee that all the numbers will be unique.

_x000D_
_x000D_
package edu.iu.common;_x000D_
_x000D_
import java.util.ArrayList;_x000D_
import java.util.Random;_x000D_
_x000D_
public class RandomCentroidLocator {_x000D_
_x000D_
public static void main(String [] args){_x000D_
 _x000D_
 int min =0;_x000D_
 int max = 10;_x000D_
 int numCentroids = 10;_x000D_
 ArrayList<Integer> values = randomCentroids(min, max, numCentroids); _x000D_
 for(Integer i : values){_x000D_
  System.out.print(i+" ");_x000D_
 }_x000D_
 _x000D_
}_x000D_
_x000D_
private static boolean unique(ArrayList<Integer> arr, int num, int numCentroids) {_x000D_
_x000D_
 boolean status = true;_x000D_
 int count=0;_x000D_
 for(Integer i : arr){_x000D_
  if(i==num){_x000D_
   count++;_x000D_
  }_x000D_
 }_x000D_
 if(count==1){_x000D_
  status = true;_x000D_
 }else if(count>1){_x000D_
  status =false;_x000D_
 }_x000D_
 _x000D_
_x000D_
 return status;_x000D_
}_x000D_
_x000D_
// generate random centroid Ids -> these Ids can be used to retrieve data_x000D_
// from the data Points generated_x000D_
// simply we are picking up random items from the data points_x000D_
// in this case all the random numbers are unique_x000D_
// it provides the necessary number of unique and random centroids_x000D_
private static ArrayList<Integer> randomCentroids(int min, int max, int numCentroids) {_x000D_
_x000D_
 Random random = new Random();_x000D_
 ArrayList<Integer> values = new ArrayList<Integer>();_x000D_
 int num = -1;_x000D_
 int count = 0;_x000D_
 do {_x000D_
  num = random.nextInt(max - min + 1) + min;_x000D_
  values.add(num);_x000D_
  int index =values.size()-1;_x000D_
  if(unique(values, num, numCentroids)){    _x000D_
   count++;_x000D_
  }else{_x000D_
   values.remove(index);_x000D_
  }_x000D_
  _x000D_
 } while (!( count == numCentroids));_x000D_
_x000D_
 return values;_x000D_
_x000D_
}_x000D_
_x000D_
}
_x000D_
_x000D_
_x000D_


You can use IntStream ints() or DoubleStream doubles() available as of java 8 in Random class. something like this will work, depends if you want double or ints etc.

Random random = new Random();

int[] array = random.ints(100000, 10,100000).toArray();

you can print the array and you'll get 100000 random integers.


You can simply solve it with a for-loop

private static double[] anArray;

public static void main(String args[]) {
    anArray = new double[10]; // create the Array with 10 slots
    Random rand = new Random(); // create a local variable for Random
    for (int i = 0; i < 10; i++) // create a loop that executes 10 times
    {
        anArray[i] = rand.nextInt(); // each execution through the loop
                                        // generates a new random number and
                                        // stores it in the array at the
                                        // position i of the for-loop
    }
    printArray(); // print the result
}

private static void printArray() {
    for (int i = 0; i < 10; i++) {
        System.out.println(anArray[i]);
    }
}

Next time, please use the search of this site, because this is a very common question on this site, and you can find a lot of solutions on google as well.


Probably the cleanest way to do it in Java 8:

private int[] randomIntArray() {
   Random rand = new Random();
   return IntStream.range(0, 23).map(i -> rand.nextInt()).toArray();
}