A random fraction below 1 is cast to an integer type, which always gives 0
What it finds
(int) Math.random() is always 0: Math.random() returns a value from 0 up to but not including 1, and the cast drops the fraction. The same holds for nextDouble() and nextFloat() of a Random. The value is meant to be scaled first, as in (int) (Math.random() * n), or nextInt(n) is meant.
From the rule's source, truncated_random.rs.
import java.util.Random; class Dice { int roll(Random random) { int a = (int) Math.random();tx0 reports: casting Math.random() to an integer always gives 0 int b = (int) (Math.random() * 6); long c = (long) random.nextDouble();tx0 reports: casting random.nextDouble() to an integer always gives 0 double d = (double) random.nextFloat(); return a + b; }} Turn it on, off or suppress it
The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:
[rules]
"tx0/java:truncated-random" = "off"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/java:truncated-random] reason="..."tx0 explain tx0/java:truncated-random shows the same in the terminal. Found a false positive? Report it.