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
You're almost there. Just add 1 to the result:
int randomInt = (int)d + 1;
This will "shift" your range to 1 - 100
instead of 0 - 99
.
or
Random r = new Random();
int randomInt = r.nextInt(100) + 1;
Here is a clean and working way to do it, with range checks! Enjoy.
public double randDouble(double bound1, double bound2) {
//make sure bound2> bound1
double min = Math.min(bound1, bound2);
double max = Math.max(bound1, bound2);
//math.random gives random number from 0 to 1
return min + (Math.random() * (max - min));
}
//Later just call:
randDouble(1,100)
//example result:
//56.736451234
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.
double random = Math.random();
double x = random*100;
int y = (int)x + 1; //Add 1 to change the range to 1 - 100 instead of 0 - 99
System.out.println("Random Number :");
System.out.println(y);
I will write int number = 1 + (int) (Math.random() * 100);