如何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) 是什么区别Math.random() * n和Random.nextInt(n)在那里n是一个整数?
以下代码仅生成0; - ;
我究竟做错了什么?
public class RockPaperSci {
public static void main(String[] args) {
//Rock 1
//Paper 2
//Scissors 3
int croll =1+(int)Math.random()*3-1;
System.out.println(croll);
}
}
Run Code Online (Sandbox Code Playgroud)
编辑,另一张海报提出修复它的东西.int croll = 1 +(int)(Math.random()*4 - 1);
感谢大家!