dimanche 22 janvier 2023

Assigning numbers 0-8 randomly to a 3x3 keypad in Android Studio

I'd like to make a game that requires numbers 0-8 to be randomly assigned (once each) to a 3x3 keypad. The buttons are named button1 to button9.
enter image description here

I thought I could do this by creating an ArrayList (called "labels") with numbers 0 to 8.

I then used the following code to assign each number in the ArrayList to a button.

Collections.shuffle(labels);
   button1.setText(String.valueOf(labels.get(0)));


   ArrayList<Integer> eight = new ArrayList<>(labels);
   eight.remove(0);
   Collections.shuffle(eight);
   button2.setText(String.valueOf(eight.get(0)));

   ArrayList<Integer> seven = new ArrayList<>(eight);
   seven.remove(0);
   Collections.shuffle(seven);

   button3.setText(String.valueOf(seven.get(0)));
   

This pattern continues all the way down to button9.

At first, I just used the one array and deleted a number from it after assigning it, but the program crashed. That's why I tried copying each array into a new one before deleting a value, but that didn't seem to help either.

When I run the new code, the program also crashes. Does anyone know why?

I was able to randomly assign numbers to the buttons with the following code, but some numbers would appear more than once (and strangely, only even numbers appeared).

Collections.shuffle(labels);
   button1.setText(String.valueOf(labels.get(0)));
   Collections.shuffle(labels);
   button2.setText(String.valueOf(labels.get(0)));
   Collections.shuffle(labels);

... to Button9.

Can anyone explain what I've done wrong?

Thanks




Aucun commentaire:

Enregistrer un commentaire