Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a random between 1 - 100 from randDouble in Java?

Tags:

java

random

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?

like image 827
George Avatar asked Oct 04 '11 02:10

George


People also ask

How do you generate a random number from 1 to 6 in Java?

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


2 Answers

or

Random r = new Random();
int randomInt = r.nextInt(100) + 1;
like image 84
MeBigFatGuy Avatar answered Sep 19 '22 08:09

MeBigFatGuy


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 shared Random objects in concurrent programs will typically encounter much less overhead and contention.

like image 36
M. Justin Avatar answered Sep 19 '22 08:09

M. Justin