2

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]);
    }
}
4
  • Hey! What do you think (int) Math.random() gives you? Commented Jun 30, 2020 at 23:34
  • 1
    Try int[] randomarray = new Random().ints(256, 1, 256 + 1).toArray(); Commented Jun 30, 2020 at 23:38
  • random numbers? Commented Jun 30, 2020 at 23:40
  • I don't know how you get zeros. Math.random() gives you pseudo-random numbers from 0 to 1 so you can just multiply it by your range e.g. 256. Commented Jul 1, 2020 at 0:22

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Good Answer. As a habit, I would use ThreadLocalRandom rather than Random.
2

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.

1 Comment

@Jack: Read the last sentence of the answer. Don't post significant code in comments please.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.