-2

i want to set buttons text by str array in random :

String str[] = { "1", "2", "3", "4", "5", "6" };
Button buttons[] = new Button[4];

        buttons[0] = (Button) findViewById(R.id.id1);
        buttons[1] = (Button) findViewById(R.id.id2);
        buttons[2] = (Button) findViewById(R.id.id3);
        buttons[3] = (Button) findViewById(R.id.id4);

for (int i = 0; i < 4; i++) {
        Random r = new Random();
        int x = r.nextInt(str.length); 
        buttons[i].setText(str[x]);
                    }

so how can i set buttons text without duplicates? something like this: enter image description here

Ali
  • 127
  • 10

2 Answers2

1

Your question is not very clear. I think this might be what you want:

1) Put the alternate button texts into an array, list or convenient structure.

2) Shuffle the array (or whatever) so the texts are in a random order with no repeats.

3) Pick off the texts in their shuffled order to assign to the buttons.

rossum
  • 15,344
  • 1
  • 24
  • 38
0
        List<Integer> setNames = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            int x;
            do {
                Random r = new Random();
                x = r.nextInt(str.length);
            }while(setNames.contains(x));
            setNames.add(x);
            buttons[i].setText(str[x]);
        }

This is another possibility. Sufficient for the four iterations.

AlbAtNf
  • 3,859
  • 3
  • 25
  • 29