I have:
private Random rng = new Random();
double random = rng.nextDouble(1.5-0.5) + 0.5;
Because I want to generate a number between 50% and 150%. However it throws me an error. How do I get a number in that range using the random function?
I have:
private Random rng = new Random();
double random = rng.nextDouble(1.5-0.5) + 0.5;
Because I want to generate a number between 50% and 150%. However it throws me an error. How do I get a number in that range using the random function?
Your problem is: you should read javadoc. Meaning: dont assume that some library method does something; instead: read the documentation to verify that your assumptions are correct.
In this case, check out Double.nextDouble ... and find:
Returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence.
The point is: there is no method nextDouble() that takes a double argument! There is only one that goes without any argument; and that method by default returns a value between 0 and 1.
So, simply change your code to call that method without any argument!
That is because nextDouble
does not receive parameters, and only return a double between 0.0 and 1.0. Use the following:
Random rng = new Random();
double max = 1.5;
double min = 0.5;
double random = rng.nextDouble(); // Double between 0.0 and 1.0
double percentage = random*(max-min) + min;
System.out.println(percentage);
If you read the error in the ide or just look at the java doc you will see clearly the reason...
method nextDouble() in the type Random is not applicable for the arguments (double)
the random class has no such a method nextDouble()
that takes a double as argument
BTW why don't you just generate a random integer between 50 and 150... that would make more sense for the implementation you desire...
something like
Random rand = new Random();
randomNum = minimum + rand.nextInt((maximum - minimum) + 1);
You can do something like 50% and 100%
public static void main(final String[] args) {
Random rng = new Random();
double random = rng.nextDouble();
if (random <= 0.5) {
System.out.println("50% " + random);
} else {
System.out.println("100% " + random);
}
}