Create an Array with random numbers

Viewed 584

How I do create an array of size 256 with sorted random numbers in the main method? I want to create an array that randomly generates numbers between 1-256, the size would be 256 as well which means it would have 256 numbers in the array and they're sorted. My code only returns me zero?

public class Array {
    public static void main(String args[]) 
    { 
        double[] randomarray = new double[256];
        for(int i = 0; i<randomarray.length;i++)
            randomarray[i] =  Math.random();
        
        for (int i = 0; i<randomarray.length;i++)
            System.out.println(randomarray[i]);
    }
}
2 Answers

Streams

As @saka1029 commented, the easiest (less code) way is by creating a IntStream, a stream of int values, produced by a call to Random.ints.

int[] sortedRandoms = 
    new Random()              // Access a random-number generator.
    .ints(256, 1, 256 + 1)    // Generate a stream of int values, an `IntStream` object.
    .sorted()                 // Sort those generated `int` values.
    .toArray();               // Return the generated `int` values in an array.

here I added sorting as well.

Math.random() returns a double between 0.0 and 1.0, and casting to an int floors doubles, so you're setting all of your array members to 0. You'll need to multiply Math.random() by your desired max value before you cast it to int.

Related