-1

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);
    }
  • You get the 2 extra elements because you do: 1. `int ListSize = (intInput3) + 1;` adding 1 to your list size for whatever reason will make the list 1 bigger than intended. 2. your loop `for (i = 0; i <= ListSize; i++)` starts at 0 and will only end when `i` get bigger than `listSize`, this will give you another extra element: So when you enter `3` for listsize you add one to it and have `listSize = 4`, then in your loop you loop starting from 0 to 4 (inclusive), meaning you will get an iteration for 0, 1, 2, 3 and 4. Which is five elements. – OH GOD SPIDERS Sep 27 '21 at 11:59
  • Does this answer your question? [How do I generate random integers within a specific range in Java?](https://stackoverflow.com/questions/363681/how-do-i-generate-random-integers-within-a-specific-range-in-java) – fantaghirocco Mar 08 '22 at 09:02

2 Answers2

0

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)

0

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);
}
Julian Kreuzer
  • 358
  • 1
  • 9