Search code examples
javaarraysrandomzero

Random() returns zero but there is no zero value


I have prepared a code to get a random number from an array of integers (1 - 10) to build a multiplication table.

    int[] anArrayOne = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int[] anArrayTwo = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int answer;
    int firstNumber = new Random().nextInt(anArrayOne.length);
    int secondNumber = new Random().nextInt(anArrayTwo.length);
System.out.println("What is" + firstNumber + " times "
+ secondNumber + "? ");

The code sometimes returns "0". Why is it the case if there is no 0 value assigned in neither of the arrays?


Solution

  • From https://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt(int)

    NextInt returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive),

    So in other words, nextInt in your case will return a value from 0 to 9 inclusive.

    If you want to use the random number as an index into an array you could do something like @haba713 's answer above/below