lundi 30 mai 2016

Shuffle method results in repeating pattern?

I have an array of JButtons with String filenames set on them as text (t's a little hard to explain but the filenames specify the images, so when I want to set an icon for a specific button, I have a method to pull the filename text from the button and use it to setIcon). The String filenames are stored in a String array, and I'm trying to shuffle the Strings around but the problem is when I run my program the filenames aren't shuffled properly. They do have random positions, but I have 24 matching pairs of filenames and the matching ones are always 3 buttons apart from each other every time I run it, which is clearly not random. Does anyone know why this is happening? I doubt it's a problem with my setFace method because I'm using the shuffled array.. help would be appreciated!

public void shuffle()
{
  for(int i = 0; i < 24; i++) 
   {
        int rand = (int)(Math.random() * 24);
        temp[i] = country[rand]; //temp is a temporary array
        country[rand] = country[i];//country is the filename array
        country[i] = temp[i];
   }

  card.setBack(cards); 
  card.setFace(country, cards); //cards is the 48 button array
 }

public void setFace(String[] file, JButton[] buttons) //filename method
{
  for(int i = 0; i < 24; i++)
  {
     buttons[i].setText(file[i]);
  }
  int ct = 0;
  for(int x = 24; x < 48; x++)
  {
     buttons[x].setText(file[ct]);
     ct++;
  }
}

public void setBack(JButton[] array) //sets back icon of card
{
  icon = new ImageIcon(this.getClass().getResource("back.png"));
  img = (icon.getImage().getScaledInstance(75, 95, java.awt.Image.SCALE_SMOOTH));
  thomas = new ImageIcon(img);

  for(int x = 0; x < array.length; x++)
  {
     array[x].setIcon(thomas);
  }
}

The non-random arrangement that I'm talking about is like this:

Card A     Card R
Card D     Card H
Card F     Card Z
Card A     Card R
Card D     Card H
Card F     Card Z




Aucun commentaire:

Enregistrer un commentaire