Java随机数但不为零
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16332938/
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
Java Random number but not zero
提问by newbieprogrammer
int num = 10;
Random rand = new Random();
int ran = rand.nextInt(num);
if (ran==0){
ran= ran+1;
}
System.out.println("random : "+ran);
This is what i have coded so far, is there a better way to do this? I feel that this is hard coding when random is 0, I added 1.
这是我到目前为止编码的内容,有没有更好的方法来做到这一点?我觉得当 random 为 0 时这是硬编码,我加了 1。
回答by Joachim Sauer
The problem with that code is that 1 is twice as likely as other numbers (as your effective result is 1 when nextInt()
returns 0 or 1).
该代码的问题在于 1 的可能性是其他数字的两倍(因为当nextInt()
返回 0 或 1时,您的有效结果为1)。
The best solution is to just alwaysadd 1 and request random numbers from a smaller range:
最好的解决方案是始终加 1 并请求较小范围内的随机数:
int rnd = rand.nextInt(num - 1) + 1;
回答by Petr Shypila
Random random = new Random;
int ran = random.nextInt(9) + 1; //10 is maxRandom value for this code. 1-10
回答by Lav
I guess you are trying to get a random number between 1 and 'num'.
我猜你想得到一个介于 1 和 'num' 之间的随机数。
a more generic way can be :
更通用的方法可以是:
int Low = 1;
int High = 10;
int R = r.nextInt(High-Low) + Low;
This gives you a random number in between 1 (inclusive) and 10 (exclusive). ( or use High=11 for 10 inclusive)
这为您提供了一个介于 1(含)和 10(不含)之间的随机数。(或使用 High=11 表示 10 包含在内)
回答by m47h
you also could do the following:
您还可以执行以下操作:
int randomNumber = 0;
do {
randomNumber = rand.nextInt(maxValue);
} while(randomNumber == 0);
回答by Vlasec
Don't expect this functionality from Random
and do it yourself as you should. One can do pretty much anything with the result - multiply, add (e.g. 2*nextInt(n)+1
for random odd number), use logarithmic scale for musical note frequencies, use a map or enum to obtain random objects ...
不要指望此功能来自Random
并按照您的意愿自行完成。人们几乎可以对结果做任何事情——乘法、加法(例如2*nextInt(n)+1
随机奇数)、对音符频率使用对数刻度、使用映射或枚举来获得随机对象......
Method nextInt(n)
is here only to give you n
different values (from 0
to n-1
). Don't ask more of it, implement the rest by yourself. If I understand your question well, you require numbers 1..9
, so you should ask for nextInt(9)+1
to get 0..8
and then add 1
.
方法nextInt(n)
在这里只是为了给你n
不同的值(从0
到n-1
)。其他的就别问了,剩下的自己实现。如果我很好地理解你的问题,你需要数字1..9
,所以你应该要求nextInt(9)+1
得到0..8
然后添加1
。
I hope this explanation helps, I saw many answers, but I didn't like the explanation in any of them.
我希望这个解释有帮助,我看到了很多答案,但我不喜欢其中任何一个的解释。
回答by Alberto Cerqueira
Try:
尝试:
int num = 10;
Random rand = new Random();
int ran = rand.nextInt(num) + 1;
回答by AG_BOSS
Try this:
尝试这个:
int num,max=10,min=1;
Random r=new Random();
num=r.nextInt(max-min)+1;
You'll need this import at the beginning of your file:
您将需要在文件开头进行此导入:
import java.util.Random;