General

Chat

Java programming help

Hey guys,

For my programming class, I need to find out how to create a random float number between 70 and 100.
I already know that the method I have to use is (float) (Math.random() *100), but I don't know how to make it generate one that isn't lower than 70 nor higher than 100.

April 19, 2012

4 Comments • Newest first

CircaSurvive

[quote=Glacier123]So you could do something like:

float ans = 0;
while (ans < 70 || ans > 100)
ans = (float) (Math.random() * 100);

Or something like that. So if it's some number lower than 70 or higher than 100, it would keep generating some number and replacing the old number with the new generated one.[/quote]

Oh right! While loops @CTBlack: we haven't really seen much yet about those prefab Java methods. Either way, thanks for helping guys!

Reply April 19, 2012
CTBlack

Random generator = new Random();
double result = (generator.nextDouble() * 30.0) + 70;

You will need to provide a seed value for Random() to make it "more" random

* Hi Hi Ky Ky *

Reply April 19, 2012
Glacier123

So you could do something like:

float ans = 0;
while (ans < 70 || ans > 100)
ans = (float) (Math.random() * 100);

Or something like that. So if it's some number lower than 70 or higher than 100, it would keep generating some number and replacing the old number with the new generated one.

Reply April 19, 2012
Omegathorion

You could try something like "if the number generated is less than 70 or higher than 100, then redo the RNG."

I don't actually know how that would be coded in Java, I took HTML/Javascript.

Reply April 19, 2012