user3358049
user3358049

Reputation: 9

random() always produce the same number?

Here is my code.

private int getRandomNumber(int start, int end) {
    Random r = new Random();
    int num = r.nextInt(end-start+1)+start; 
    return num;
}   

I am implementing a GUI with a button that would generate a random password length each time I click the button. So I set passlength:

passLength = getRandomNumber(min,max);

and when I print out passLength, it give me the same number(the min number,in fact) each time I click it. How do I make it so that I can generate a different number every click?

Upvotes: 0

Views: 90

Answers (2)

Hal50000
Hal50000

Reputation: 639

I suspect your problem is elsewhere. I tested the following code and got what would be expected: psuedorandoms in [start, end]. Instantiating the Random class once or every time makes no difference.

import java.util.Random;

public class TestRandom {

    public TestRandom () {
        for (int i = 0; i < 30; i++) {
            System.out.print(getRandomNumber(0,200) + " ");
        }
    }

    private int getRandomNumber(int start, int end) {
        Random r = new Random();
        int num = r.nextInt(end-start+1)+start;
        return num;
    }
}

Sample results were:

190 177 137 184 146 177 54 110 148 172 127 130 110 152 161 197 181 156 33 191 0 62 130 31 35 82 3 123 88 122

101 160 145 174 179 81 73 78 84 10 59 14 189 145 41 198 133 72 129 96 79 104 184 178 55 56 142 14 70 14

109 18 136 20 13 47 67 0 96 179 29 127 11 128 147 143 92 160 144 194 192 194 89 25 67 181 102 154 33 152

etc.

Upvotes: 0

keshlam
keshlam

Reputation: 8058

Don't create a new random-number generator (new Random()) every time. Create one, assign it to a persistent variable (member or static), and call it repeatedly.

Upvotes: 1

Related Questions