47

Possible Duplicate:
Java: generating random number in a range

How do I generate a random integer i, such that i belongs to (0,10]?

I tried to use this:

Random generator = new Random();
int i = generator.nextInt(10);

but it gives me values between [0,10).

But in my case I need them to be (0,10].

Community
  • 1
  • 1
Dinara
  • 523
  • 1
  • 6
  • 9

3 Answers3

83
Random generator = new Random(); 
int i = generator.nextInt(10) + 1;
Dmitry B.
  • 9,107
  • 3
  • 43
  • 64
  • This generates integers in the range [1, 11). – Nick Meyer Nov 23 '11 at 01:15
  • 24
    ... which, now that I realize we're talking about integers, is the same :) – Nick Meyer Nov 23 '11 at 01:16
  • Well, adding "1" solves the problem for sure, but I just can't understand WHY this method does not handle two arguments - start and stop of the range?! – thorinkor May 12 '14 at 12:23
  • 1
    @thorinkor Passing both integers would require copying both values onto the stack for use inside the method. The only purpose of the value '1' in this instance is basic addition. There's no reason to introduce extra overhead for a single operation that can be done externally in less than one line of code. – bindsniper001 Jul 16 '14 at 04:44
  • 3
    @bindsniper001 it makes it cleaner, it's like the `isEmpty()` method where you could just do `.size() == 0`. – Sled Jul 29 '14 at 21:17
15

How about:

Random generator = new Random();
int i = 10 - generator.nextInt(10);
Nick Meyer
  • 39,212
  • 14
  • 67
  • 75
5

Just add one to the result. That turns [0, 10) into (0,10] (for integers). [0, 10) is just a more confusing way to say [0, 9], and (0,10] is [1,10] (for integers).

Thilo
  • 257,207
  • 101
  • 511
  • 656
  • Well, adding "1" solves the problem for sure, but I just can't understand WHY this method does not handle two arguments - start and stop of the range?! – thorinkor May 12 '14 at 12:23