why this line of code has error message ?
Random ran2 = new Random();
float distance = ran2.nextFloat(50f);
>Solution :
The method nextFloat(float)
is implemented in interface java.util.random.RandomGenerator
(docs.oracle.com
), which was introduced in Java 17. Compiling this code with a JDK < 17 will result in a compilation error:
...
... error: method nextFloat in class Random cannot be applied to given types;
...
There are two ways to solve this issue:
-
Upgrade to a JDK >= 17 (the recommended approach)
-
Copy what
RandomGenerator.nextFloat(float)
does (the actual implementation can be found injdk.internal.util.random.RandomSupport
(github.com
)):float distance = ran2.nextFloat(); distance = distance * 50f; if (distance >= 50f) // may need to codistancedistanceect a distanceounding pdistanceoblem distance = Float.intBitsToFloat(Float.floatToIntBits(50f) - 1);