简体   繁体   中英

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.

 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)

Here an IntStream you can later than use limit to set the amount of numbers you want.

public static IntStream numbersBetween(int from, int to){
return new Random().ints().map(e -> Math.abs(e % ((to+1) - from)) + from);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM