1

I want this program to bring back a new set of numbers every time the 'Generate Number' button is clicked, that is 6 integer numbers between 0 and 10.

GUI for the program

However, it brings back the same set of numbers even after clicking the button again and again.

This is the Model class code that generates the number:

public class Number {
    int[] num = new int[6];
    Random ran = new Random(10);

    public int[] generate(){

        for(int i = 0; i<6; i++)
        {
            num[i] = ran.nextInt(10);
        }
        return num;
    }
}

and this is how this code gets called from the ActionListener method:

public void actionPerformed(ActionEvent e) {
    Number numb = new Number();
    lot_num.setText(Arrays.toString(numb.generate()));

}

I also can't tell how to manage the format of the result so that it is spaced through the text field without the commas and the brackets.

Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
Seif
  • 566
  • 2
  • 10
  • 21
  • @SotiriosDelimanolis: I'm not sure that they *knew* that they were setting the seed, necessarily. – Makoto Nov 12 '15 at 22:51
  • Sort of relevent about [randomness](http://dilbert.com/strip/2001-10-25) – Brandon Laidig Nov 12 '15 at 22:52
  • replace `Random ran = new Random(10);` with `static final Random ran = new Random();` – Iłya Bursov Nov 12 '15 at 22:52
  • 1
    @Lashane: It doesn't need to be static. – Makoto Nov 12 '15 at 22:53
  • 2
    @Makoto What difference does that make? The answers in the linked post explain all of this. – Sotirios Delimanolis Nov 12 '15 at 22:53
  • @Makoto in this case its needs to be static, otherway you will create new Random every time you click on button, so in case of very fast click - you still have chance to get the same seed – Iłya Bursov Nov 12 '15 at 22:54
  • 2
    @Lashane: That's not true; it's a field in their `Number` class. Perhaps the instance of `Number` where the event is called needs to be pulled up to a field, but that doesn't mean it needs to be static. – Makoto Nov 12 '15 at 22:55
  • @Makoto `That's not true;` - nope, its true. `Perhaps the instance of Number where the event is called needs to be pulled up` - its another solution to the problem, which also will work – Iłya Bursov Nov 12 '15 at 22:57

1 Answers1

7

You've seeded your PRNG. You're not going to get any different values with that.

Simply remove the seed on initialization.

Random ran = new Random();
Makoto
  • 104,088
  • 27
  • 192
  • 230