据我所知,这段代码不应该编译或运行,因为 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)