[英]How to generate a certain amount of random numbers within a range in Java?
I'm trying to make a small program that allows you to generate a certain amount of numbers within a range, but it does not work as expected.我正在尝试制作一个小程序,允许您生成一定范围内的一定数量的数字,但它没有按预期工作。
For example, if I ask the program to generate 3 random numbers between 5 and 10 it gives me 5 random numbers between 0 and 5.例如,如果我要求程序生成 5 到 10 之间的 3 个随机数,它会给我 5 个 0 到 5 之间的随机数。
private void jFillActionPerformed(java.awt.event.ActionEvent evt) {
int intInput1;
int intInput2;
int intInput3;
int i;
int RandomNumber;
intInput1 = Integer.parseInt(txtInput1.getText());
intInput2 = Integer.parseInt(txtInput2.getText());
intInput3 = Integer.parseInt(txtInput3.getText());
int ListSize = (intInput3) + 1;
Random rnd = new Random();
for (i = 0; i <= ListSize; i++)
{
RandomNumber = rnd.nextInt((intInput2 - intInput1) + 1);
fill.addElement(RandomNumber);
lstNumbers.setModel(fill);
}
Simply always add 5
(or more specifically - intInput1
in your case as it seems it's lower range value) to generated numbers so it will be in the range you need (0+5=5, 5+5=10 so it will be in range 5,10)只需将
5
(或更具体地说 - 在您的情况下为intInput1
,因为它似乎是较低的范围值)添加到生成的数字中,这样它就会在您需要的范围内(0+5=5、5+5=10,所以它会在范围 5,10)
Here an IntStream you can later than use limit to set the amount of numbers you want.这里有一个 IntStream,您可以稍后使用 limit 来设置您想要的数字数量。
public static IntStream numbersBetween(int from, int to){
return new Random().ints().map(e -> Math.abs(e % ((to+1) - from)) + from);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.