Generating random floating point values to cast them into integers is inefficient. A random bounded integer value can be generated with a single
proper method call. Use nextInt
to make the code more efficient and the intent clearer.
Noncompliant code example
Random r = new Random();
int rand = (int) (r.nextDouble() * 50); // Noncompliant way to get a pseudo-random value between 0 and 50
int rand2 = (int) r.nextFloat(); // Noncompliant; will always be 0;
Compliant solution
Random r = new Random();
int rand = r.nextInt(50); // returns pseudo-random value between 0 and 50
int rand2 = 0;