Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

nextFloat is not working on Random object

why this line of code has error message ?

Random ran2 = new Random();
float distance = ran2.nextFloat(50f);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 in jdk.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);
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading