Okay, I'm still fairly new to Java. We've been given an assisgnment to create a game where you have to guess a random integer that the computer had generated. The problem is that our lecturer is insisting that we use:
double randNumber = Math.random();
And then translate that into an random integer that accepts 1 - 100 inclusive. I'm a bit at a loss. What I have so far is this:
//Create random number 0 - 99
double randNumber = Math.random();
d = randNumber * 100;
//Type cast double to int
int randomInt = (int)d;
However, the random the lingering problem of the random double is that 0 is a possibility while 100 is not. I want to alter that so that 0 is not a possible answer and 100 is. Help?
For example, in a dice game possible values can be between 1 to 6 only. Below is the code showing how to generate a random number between 1 and 10 inclusive. Random random = new Random(); int rand = 0; while (true){ rand = random. nextInt(11); if(rand !=
or
Random r = new Random();
int randomInt = r.nextInt(100) + 1;
The ThreadLocalRandom
class provides the int nextInt(int origin, int bound)
method to get a random integer in a range:
// Returns a random int between 1 (inclusive) & 101 (exclusive)
int randomInt = ThreadLocalRandom.current().nextInt(1, 101)
ThreadLocalRandom
is one of several ways to generate random numbers in Java, including the older Math.random()
method and java.util.Random
class. The advantage of ThreadLocalRandom
is that it is specifically designed be used within a single thread, avoiding the additional thread synchronization costs imposed by the other implementations. Therefore, it is usually the best built-in random implementation to use outside of a security-sensitive context.
When applicable, use of
ThreadLocalRandom
rather than sharedRandom
objects in concurrent programs will typically encounter much less overhead and contention.
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