我想在Java中生成1到10之间的数字.
这是我尝试过的:
Random rn = new Random();
int answer = rn.nextInt(10) + 1;
Run Code Online (Sandbox Code Playgroud)
有没有办法告诉()在调用nextInt方法时要在括号中放什么以及添加什么?
请考虑以下代码:
int rand = new Random().nextInt((30 - 20) + 1) + 20
Run Code Online (Sandbox Code Playgroud)
它将返回30到20之间的随机数.但是,我需要它的范围包括负数.我如何在这一代中包含负数?我尝试过使用数学会产生负面影响,但这会导致错误.简单地减去或添加负数不会产生所需的值.
编辑:对不起,我只是半醒.正确的代码是int rand = new Random().nextInt((30 - 20) + 1) + 20;.