Reputation: 133
The desired output is a random float between two floats. This is the way I did it but this method doesn't work for negative floats like: random float between -1f and -30f since the bound has to be positive and I get IllegalArgumentException. It also looks pretty complicated...if you have an easier approach that would be lovely. Cheers!
unitsConsumed = rnd.nextInt(Math.round(maxUnitsConsumed-minUnitsConsumed))+minUnitsConsumed;
Where rnd is an instance of Random.
Upvotes: 3
Views: 1403
Reputation: 260
Try with
public static void main(String[] args) {
Random rand = new Random();
float result = rand.nextFloat() * (-1f - (-30f)) + (-30f);
System.out.println(result);
}
Upvotes: 3
Reputation: 89
You can achieve this by using the code below where min is your minimum value and max is your maximum value:
float random= rnd.nextFloat() * (max - min) + min;
Upvotes: 6