-1

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);
         }
    }
}
Jonas
  • 121,568
  • 97
  • 310
  • 388
Sean M
  • 79
  • 1
  • 9
  • Did you read the documentation for the method you're calling? The comment in your own code says that the upper bound is exclusive ("excl")... how would you expect to get an answer of 11 if `nextInt(10)` can only return a value up to 9, and you're adding 1 to that? – Jon Skeet Jan 13 '16 at 09:59
  • Yeah i realize now i made a stupid mistake. I did read it, but it didn't sink in for some reason. Sorry for the bad post. – Sean M Jan 13 '16 at 10:00
  • you follow this post it is already discuss http://stackoverflow.com/questions/363681/generating-random-integers-in-a-range-with-java http://stackoverflow.com/questions/20389890/generating-a-random-number-between-1-and-10-java – amit prasad Jan 13 '16 at 10:01
  • @SeanM - if you consider it a bad post, you can always delete it using the link under the question. Welcome to StackOverflow! – Adam Michalik Jan 13 '16 at 10:13
  • Thank you for the warm welcome ahaha. I have a lot to learn! Unfortunately I can't delete it any more. – Sean M Jan 13 '16 at 10:24

1 Answers1

8

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)

Eran
  • 387,369
  • 54
  • 702
  • 768