math.random,只生成一个0?
下面的代码只是产生一个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); } } 编辑,另一张海报提出了一些解决scheme。 int croll = 1 +(int)(Math.random()* 4 – 1);
感谢大家!
 你正在使用Math.random()这个状态 
返回具有正号的
double值,大于或等于0.0且小于1.0。
 您将结果转换为一个int值,该值返回值的整数部分,即0 。 
 然后1 + 0 - 1 = 0 。 
 考虑使用Random 
 Random rand = new Random(); System.out.println(rand.nextInt(3) + 1); 
  Math.random()在范围 – [0.0, 1.0) Math.random()之间生成double值。 然后你已经把结果input为int : 
 (int)Math.random() // this will always be `0` 
 然后乘以3是0 。 所以,你的表情真的是: 
 1 + 0 - 1 
我想你想把这样的括号:
 1 + (int)(Math.random() * 3) 
 话虽如此,如果您想要在某个范围内生成整数值,您应该使用Random#nextInt(int)方法。 这比使用Math#random()更高效。 
你可以像这样使用它:
 Random rand = new Random(); int croll = 1 + rand.nextInt(3); 
也可以看看:
- Math.random()与Random.nextInt(int)
在Java中随机生成0或1的最简单方法之一:
  (int) (Math.random()+0.5); or (int) (Math.random()*2); 
我们所有的伴侣都解释了你得到意想不到的结果的原因。
 假设你想要生成一个随机的croll 
 考虑Random的决议 
  Random rand= new Random(); double croll = 1 + rand.nextInt() * 3 - 1; System.out.println(croll); 
 public static double random() 
返回具有正号的double值,大于或等于0.0且小于1.0。 返回值是从该范围内(近似)均匀分布伪随机select的。
  int croll =1+(int)Math.random()*3-1; 
例如
  int croll =1+0*-1; System.out.println(croll); // will print always 0