2

In Java, I am trying to populate an array with random numbers. The array has to be the size that the user inputs. For example, if the user enters 6, then the array must have 6 numbers in it. This is what I have for this program so far. It compiles and runs, but prints out only 0's. I am a little new to Java.

{
    System.out.println("Enter a number: " );

    int number = scan.nextInt();

    int [] integerArray = new int[number];
    for (int i=0; i < number; i++)
    {
        integerArray[i] = (int)(Math.random());
    }
    System.out.println(Arrays.toString(integerArray));
}
Jim Nguyen
  • 31
  • 1
  • 4
    `Math.random()` returns a double between 0 (inclusive) and 1 (exclusive). So if you cast it to an int, it's always going to be 0. Multiply `Math.random()` by some amount, e.g. `number`. – Andy Turner Jun 30 '17 at 16:47
  • Check out https://stackoverflow.com/questions/2444019/how-do-i-generate-a-random-integer-between-min-and-max-in-java as well – bradimus Jun 30 '17 at 16:48
  • https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#nextInt-int- – Leos Literak Jun 30 '17 at 16:48

2 Answers2

1

java.util.Random has a method to supply an array with random integer values; consider the following:

Random random = new Random();

Scanner scanner = new Scanner(System.in);

int[] array = random.ints(scanner.nextInt()).toArray();

The documentation if you're curious.

Jacob G.
  • 28,856
  • 5
  • 62
  • 116
0

Math.random() returns a double between 0 (inclusive) and 1 (exclusive).

So if you cast it to an int, it's always going to be 0.

Multiply the result of Math.random() by some amount, e.g. number.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243