Creating a random number generator in Java - looking at num1 and num2, in which instances would I use either of these methods for creating a random number between 1 and 8? Is one more efficient than the other, any other benefits?
import java.util.*;
public class Chpt3 {
public static void main(String[] args) {
Random rand = new Random();
int num1 = Math.abs(rand.nextInt()) % 8 + 1;
int num2 = rand.nextInt(8) + 1;
System.out.println(num1);
System.out.println(num2);
}
}
nextInt(n) returns between 0 and n-1.
So to get between 1 to 8,
int num2 = rand.nextInt(8) + 1;
Which means your second one is the one you need.
Update:
Math.abs(Integer.MIN_VALUE) returns negative value.
According to this answer on SO:
Integer.MIN_VALUE is -2147483648, but the highest value a 32 bit integer can contain is+2147483647. Attempting to represent+2147483648in a 32 bit int will effectively "roll over" to-2147483648. This is because, when using signed integers, the two's complement binary representations of+2147483648and-2147483648are identical. This is not a problem, however, as+2147483648is considered out of range.For a little more reading on this matter, you might want to check out the Wikipedia article on Two's complement.
First method just contains a rare corner case. That's why it's better to use second one as it's safe.
Math.abs(rand.nextInt()) % 8 + 1;
This has a subtle bug. Math.abs(Integer.MIN_VALUE) returns MIN_VALUE which is a negative number. A simpler solution is
(rand.nextInt() & 7) + 1;
This will always be non-negative and be slightly faster.
rand.nextInt(8) + 1
This is both faster, but more importantly, clearer as to what you are trying to achieve. For the later reason, rather than speed alone, it is the better choice.
Note: You could use abs if you really wanted to like this. However this is not as clean as the nextInt call.
Math.abs(rand.nextInt() % 8) + 1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With