-6

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?

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
CyberMaestro
  • 15
  • 1
  • 5
  • 2
    "It throws me an error" isn't a helpful description. Please include the exception stack trace in your questions! – GhostCat Nov 13 '16 at 20:35
  • If you fix the error, it will probably work. – Kayaman Nov 13 '16 at 20:35
  • Welcome to Stack Overflow! Please review our [SO Question Checklist](http://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist) to help you to ask a good question, and thus get a good answer. – Joe C Nov 13 '16 at 20:38

4 Answers4

1

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!

GhostCat
  • 137,827
  • 25
  • 176
  • 248
1

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);
Jose Da Silva Gomes
  • 3,814
  • 3
  • 24
  • 34
1

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);
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
-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);
    }
}
Tanmay Baid
  • 459
  • 4
  • 19