How to set a different random number to all button

2019-05-17 06:47发布

问题:

I have 4 buttons in an array. I am able to generate a random number and set it to all those buttons, but that's not what I intend to do. What I really want to do it set a random number to each button. E.g: instead of having '17' inside all four buttons, I may have '18', '15', '10', and '11' in each button. Instead of manually assigning a random in to each button, how could I do this to all buttons?

Here's my code:

Random rbselection = new Random();
final int rbselector = rbselection.nextInt(4);
final Button[] selectrb = new Button[4];
selectrb[0] = rb1;
selectrb[1] = rb2;
selectrb[2] = rb3;
selectrb[3] = rb4;
Random randoms1 = new Random();
int setRandoms1 = randoms1.nextInt(10);
for(int allrbA=0; allrbA<4; allrbA++) {
    selectrb[allrbA].setText(""+setRandoms1);
}

Also, does anyone know how to stop a single number from being outputted twice when doing this? For example if the random numbers set are between 10 and 20 and one of them is 12, anyone know how to make all other possible numbers anything between that range apart from 12?

回答1:

Try this:

    Random rnd = new Random();
    for(int allrbA=0; allrbA<4; allrbA++)
        selectrb[allrbA].setText(String.valueOf(rnd.nextInt(20)));


回答2:

If I were you..

public static void main(String[] args) {
    Set<Integer> uniqueRandomNumbers = new LinkedHashSet<>();

    while (uniqueRandomNumbers.size() != 4) {
        Random random = new Random();
        uniqueRandomNumbers
                .add(Math.abs(Integer.valueOf(random.nextInt())));
    }
    System.out.println(uniqueRandomNumbers);
}

Explanation : I am generating random numbers. First I got random number 100, I added it to a 'Set' as set always maintains the uniqueness, if I get 100 again by any chance the size of the Set won't be increasing.

When size of the Set is 4 the loop breaks and the set contains unique random numbers.

Iterate through the Set to set the text.



回答3:

To get random number in Java:

Random rand = new Random();

int  n = rand.nextInt(50) + 1;

Where 1 is going to be your minimum in the range and 50 is going to be your max. Use this link for reference: Getting random numbers in Java

Depending on how many buttons you have. You could have

rbselection.nextInt(50) + 1;

to generate a new Int between 1 to 50 range every time u call it and add it to some list or Set.

So something like this:

Random rand = new Random();
int  n = rand.nextInt(50) + 1;

ArrayList<Integer> ar = new ArrayList<Integer>();
int i = 0;

while (i < 4)
{    
    int temp = rbselection.nextInt(50) + 1;
    if (ar.contains(temp))
        continue;

    ar.Add(temp);
    i++;
}

Also, u can change the above code to something like:

while (i < 4)
{
    int temp = rbselection.nextInt(50) + 1;
    if (ar.contains(temp))
        continue;

    array[i].setText(temp);
    ar.Add(temp);
    i++;
}

Where array is the button array of size 4.