rspec/rules/S2140/java/rule.adoc

46 lines
988 B
Plaintext

== Why is this an issue?
Generating random floating point values to cast them to 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
[source,java]
----
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
[source,java]
----
Random r = new Random();
int rand = r.nextInt(50); // returns pseudo-random value between 0 and 50
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Use "java.util.Random.nextInt()" instead.
'''
== Comments And Links
(visible only on this page)
=== on 11 Oct 2014, 11:58:06 Freddy Mallet wrote:
Sounds good for me !
endif::env-github,rspecator-view[]