mardi 10 novembre 2020

Is there a more effective way to give random values to Button elements in Android Studio?

I have 4 Button elements in a row in my Activity. I have four statis value and I want to assign these values to buttons randomly, after each button push.

At the moment I wrote a generator method which generates 4 different values and set the button values to them. I'm wondering, maybe there's a more effective tool to do this task in Android?

The generator:

public void generator(View view) {
        int one = new Random().nextInt(4);
        int two;
        do {
            two = new Random().nextInt(4);
        } while (two == one);
        int three;
        do {
            three = new Random().nextInt(4);
        } while (three == one || three == two);
        int four;
        do {
            four = new Random().nextInt(4);
        } while (four == one || four == two || four == three);
        buttonOnebutton.setText(String.valueOf(one));
        buttonTwobutton.setText(String.valueOf(two));
        buttonThreebutton.setText(String.valueOf(three));
        buttonFourbutton.setText(String.valueOf(four));
    }



Aucun commentaire:

Enregistrer un commentaire