如何int在特定范围内生成随机值?
我试过以下,但那些不起作用:
尝试1:
randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.
Run Code Online (Sandbox Code Playgroud)
尝试2:
Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum = minimum + i;
// Bug: `randomNum` can be smaller than `minimum`.
Run Code Online (Sandbox Code Playgroud) 我想在Java中生成1到10之间的数字.
这是我尝试过的:
Random rn = new Random();
int answer = rn.nextInt(10) + 1;
Run Code Online (Sandbox Code Playgroud)
有没有办法告诉()在调用nextInt方法时要在括号中放什么以及添加什么?