Search code examples
javarandomiterator

Why does int answer = generator.nextInt(10) + 1; only produce numbers between 1 and 10?


I don't understand why it wouldn't generate upwards of 11.

Here is my tester code:

import java.util.Random;

public class randomNumberTest
{
    public static void main(String[] args)
    {
         Random rn = new Random();
         //tests random number generator (between 1(inc) and 10(excl))
         for(int i =0; i < 100; i++)
         {
             int answer = rn.nextInt(10) + 1;
             System.out.println(answer);
         }
    }
}

Solution

  • Read the Javadoc. rn.nextInt(10) generates numbers from 0 to 9. Adding 1 gives you a range from 1 to 10.

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