0

I wrote the code to create user desired number of array and size, but there is no any random number displayed.

public class ArrayStats {
    public static void fillRandomArray(int [] a, int max) {
        int [] randomArray = new int[max];
        for (int i=0; i < randomArray.length; i++){
            randomArray[i] = (int)(Math.random());
        }
    }
}
dur
  • 15,689
  • 25
  • 79
  • 125
K. Ji
  • 55
  • 9

3 Answers3

0

The problem is that Math.random() return a Double value from 0.0 to 1.0 0.1 to int = 0, ....... 0.5 to int = 0 . If you need generate random number try it:

    public static int randomNumber(int min, int max) {

            Random rand = new Random();
            int num = rand.nextInt(max - min + 1) + min;
            return num;

        }

 public static void fillRandomArray(int [] a, int max) {
        int [] randomArray = new int[max];
        for (int i=0; i < randomArray.length; i++){

            //Example Generate random number between 1 and 9
            randomArray[i] = randomNumber(1,9);
        }

    }
toto
  • 1,180
  • 2
  • 13
  • 30
0

Here's a tiny modification to your code, that would fill your array with random ints from 0 to Integer.MAX_VALUE:

public class ArrayStats {
    public static void fillRandomArray(int [] a, int max) {
        int [] randomArray = new int[max];
        for (int i=0; i < randomArray.length; i++){
            randomArray[i] = (int)(Math.random() * Integer.MAX_VALUE);
        }
    }
}

The thing here is that Math.random() returns a double in the range from 0 to 1. When you were casting it to (int) it always turned 0.

Alternatively you can take a look at class Random.

0

The random values aren't stored because function Math.random() generates values between 0.0 (inclusive) and 1.0 (exclusive) and hence, cast to int will always return 0. From official docs:

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.

Either multiply the Math.random() result with some fixed integer value and cast to int or use a Random instance's method random.nextInt() as:

int rand = (int)(Math.random() * FIXED_INT_VAL);

or

Random r = new Random();
int rand = r.nextInt();

The latter approach is recommend due to reason explained in this post.

So, your code becomes:

public class ArrayStats {
    public static void fillRandomArray(int [] a, int max) {
        int [] randomArray = new int[max];
        Random r = new Random();
        for (int i=0; i < randomArray.length; i++){
            randomArray[i] = r.nextInt();
        }
    }
}
Community
  • 1
  • 1
Gurwinder Singh
  • 38,557
  • 6
  • 51
  • 76