The method proposed by Karl isn't quite right; the smallest value that it can return is a + 1, not a. (In fairness, he said right out that he didn't test the code.)
That said, there's a much better way to get a random integer between a and b: user Random.nextInt(int n), which returns a random integer from 0 (inclusive) to n, exclusive. Here's a method to return a random integer from a to b, inclusive:
<pre>
private static Random random = new Random();
static int rnd(int min, int max) {
return random.nextInt(max - min + 1) + min;
}
</pre>
Note that it's much more common in Java to express ranges from
min, inclusive, to
max, exclusive. To make the method obey this convention, simply eliminate the
+ 1.
A great advantage of this method over Karl's is that it is easy to prove that it works (i.e., returns each of the integers in the range with equal likelihood). This is because the method takes advantage of a library method that does the hard work for you (Random.nextInt(int)). A second advantage is that it's much faster. I discuss this in more detail in Item 30 of my
book ("Know and use the libraries").
------------------
Joshua Bloch
Author of
Effective Java