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].

0

3 Answers 3

83
Random generator = new Random(); 
int i = generator.nextInt(10) + 1;
Sign up to request clarification or add additional context in comments.

5 Comments

This generates integers in the range [1, 11).
... which, now that I realize we're talking about integers, is the same :)
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 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 it makes it cleaner, it's like the isEmpty() method where you could just do .size() == 0.
15

How about:

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

2 Comments

+1 1/2 for cleverness and -1/2 for obtuseness.
Yes, definitely obtuse. I was originally thinking real numbers, but at least it still works for integers! :)
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).

1 Comment

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?!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.