cuy*_*ken 1 java random parameters
据我所知,这段代码不应该编译或运行,因为 Random 没有带有两个参数的 nextInt 方法。但它确实运行并生成从 -5 到 5(包含 -5 和 5)的数字。
import java.util.Random;
public class RandomNextIntParameters {
public static void main(String[] args) {
Random rand = new Random();
int a = rand.nextInt(-5, 5); // why does this work?
while (a >= 0) {
System.out.println(a);
a = rand.nextInt(-5, 5);
}
System.out.println(a); // prints a negative number
}
}
Run Code Online (Sandbox Code Playgroud)
RandomGenerator#nextInt我假设您(至少)使用的是 Java 17,它引入了RandomGenerator具有nextInt(origin, bound)方法的新接口。
从 Java 17 开始,Random实现该RandomGenerator接口,从而实现该nextInt方法。
根据该方法的描述:
返回在指定原点(包括)和指定边界(不包括)之间伪随机选择的 int 值。
有关更多详细信息,请参阅JEP 356:增强型伪随机数生成器。
| 归档时间: |
|
| 查看次数: |
1212 次 |
| 最近记录: |