herpderp
herpderp

Reputation: 16177

Random.nextFloat is not applicable for floats?

float minX = 50.0f;
float maxX = 100.0f;

Random rand = new Random();

float finalX = rand.nextFloat(maxX - minX + 1.0f) + minX;

"The method nextFloat() in the type Random is not applicable for the arguments (float)"

Um, what?

Upvotes: 16

Views: 53867

Answers (4)

Bill the Lizard
Bill the Lizard

Reputation: 405775

The nextFloat method doesn't take an argument. Call it, then scale the returned value over the range you want.

float minX = 50.0f;
float maxX = 100.0f;

Random rand = new Random();

float finalX = rand.nextFloat() * (maxX - minX) + minX;

Upvotes: 79

Anthony Accioly
Anthony Accioly

Reputation: 22471

Random only return floats between 0 and 1.0 (no overloaded version like for integers): See the Javadocs here: http://download.oracle.com/javase/6/docs/api/java/util/Random.html#nextFloat()

I think you can do what you are intending with:

float finalX = (maxX - minX) * rand.nextFloat() + minX;

Upvotes: 4

tjg184
tjg184

Reputation: 4676

It should read like the following as others are suggesting.

float finalX = rand.nextFloat();
// do other stuff

Upvotes: 0

entonio
entonio

Reputation: 2173

The documentation is very clear, nextFloat() doesn't take any arguments. It'll give you a number between 0 and 1, and you'll need to use that in your calculation.

edit: example

private Random random = new Random();
public float nextFloat(float min, float max)
{
    return min + random.nextFloat() * (max - min)
}

Upvotes: 0

Related Questions