To generate a random decimal from [0-100) you can use Math.random() as you are already, or you can use a Random
object
Do note by [0-100), these bits of code return numbers from 0 up to, but not including, 100
Math.random():
double xPos = Math.random() * 100;
double yPos = Math.random() * 100;
Math.random() with 1 decimal place:
double xPos = Math.floor(Math.random() * 1000) / 10;
double yPos = Math.floor(Math.random() * 1000) / 10;
Random object:
Random r = new Random();
double xPos = r.nextDouble() * 100;
double yPos = r.nextDouble() * 100;
Random object with 1 decimal place:
Random r = new Random();
double xPos = r.nextInt(1000) / 10.0;
double yPos = r.nextInt(1000) / 10.0;
It is considered better practice to use the Random
object, even though Math.random()
calls its own internal Random
object.
Using Random
instead of Math.random()
does have the benefit of easier concurrency. Without multiple Random
objects, multithreading with heavy usage of randomized numbers will slow down to a crawl