简体   繁体   中英

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);
         }
    }
}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM