java nextFloat对随机对象不起作用[已关闭]

nhaq1z21  于 2023-01-11  发布在  Java
关注(0)|答案(1)|浏览(124)

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
3天前关闭。
Improve this question
为什么这行代码有错误信息?

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

j8yoct9x1#

方法nextFloat(float)在接口java.util.random.RandomGenerator ( docs.oracle.com )中实现,该接口是在Java 17(en.wikipedia.org)中引入的。
使用JDK〈17编译此代码将导致编译错误:

...
... error: method nextFloat in class Random cannot be applied to given types;
...

有两种方法可以解决此问题:

  • 升级到JDK〉= 17(推荐方法)
  • 复制RandomGenerator.nextFloat(float)的功能(实际实现可以在jdk.internal.util.random.RandomSupportgithub.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);

相关问题