Java中的随机函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9847169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
random function in Java
提问by Johnny Dahdah
I want to know how to get a 4-digit random number in Java. I was trying to do it and everytime I run the program I always get the same number. Thanks
我想知道如何在 Java 中获取 4 位随机数。我正在尝试这样做,每次运行该程序时,我总是得到相同的数字。谢谢
采纳答案by kullalok
int randomNumber = ( int )( Math.random() * 9999 );
if( randomNumber <= 1000 ) {
randomNumber = randomNumber + 1000;
Math.random() is a method that generates a random number through a formula. It returns a double however, so casting is required if you want an integer, float, or etc. The if block makes sure that the number is above 1000 and is a 4-digit number.
Math.random() 是一种通过公式生成随机数的方法。然而,它返回一个双精度值,因此如果您想要一个整数、浮点数等,则需要进行强制转换。 if 块确保该数字大于 1000 并且是一个 4 位数字。
回答by mehrmoudi
回答by Adam
Working solution - different number each time
工作解决方案 - 每次不同的数字
Random r = new Random();
int fourDigit = 1000 + r.nextInt(10000);
System.out.println(fourDigit);
Broken - same number every time
坏了 - 每次都一样的数字
Random r = new Random(123); // <---- uses same seed every time !
int fourDigit = 1000 + r.nextInt(9000);
System.out.println(fourDigit);