重新创建阵列

时间:2012-03-10 17:01:48

标签: java arrays

我正在尝试制作一副纸牌,每个套装的阵列都在一副牌中。当绘制一张牌时,它也会从它所属的套装阵列中移除。当有人调用shuffle方法时,它将“重新创建”这些数组。我需要帮助来解决这个问题。

public class Deck {

  private static String[] hearts = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "jack", "queen", "king", "ace"};
  private static String[] diamonds = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "jack", "queen", "king", "ace"};
  private static String[] clubs = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "jack", "queen", "king", "ace"};
  private static String[] spades = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "jack", "queen", "king", "ace"};
  private static int cardsLeft = 52;


  public static void shuffle() {

      /*
       * This method will shuffle the deck. It will simply recreate
       * the arrays after the cards have been deleted from being dealt.
       */

      hearts = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "jack", "queen", "king", "ace"};
      diamonds = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "jack", "queen", "king", "ace"};
      clubs = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "jack", "queen", "king", "ace"};
      spades = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "jack", "queen", "king", "ace"};
      cardsLeft = 52;
  }
}

我在顶部创建数组,然后尝试用shuffle方法中的原始数据覆盖它。

请不要帮助其他任何事情 - 我想自己这样做,我只是在寻求这个问题的帮助。

谢谢!

3 个答案:

答案 0 :(得分:2)

使用以下语法:

hearts = new String[]{"1","2","3",...};

无论如何,如果删除元素,我建议使用list而不是array。

答案 1 :(得分:2)

如上所述,请使用List接口的实例而不是数组,并使用使用Collections.shuffle(List list);方法,而不是编写自己的。重命名{{ 1}}方法,因为它的名字与它实际上相比是非常违反直觉的。

答案 2 :(得分:2)

如前所述,只需使用Java集合中的List。

快速而肮脏的例子:

private static ArrayList<String> hearts;
private static ArrayList<String> diamonds;
private static ArrayList<String> clubs;
private static ArrayList<String> spades;
private static int cardsLeft = 52;

static {
    hearts = new ArrayList<String>();
    diamonds = new ArrayList<String>();
    clubs = new ArrayList<String>();
    spades = new ArrayList<String>();

    for(int i = 0; i <= 10; i++) {
        hearts.add(Integer.toString(i));
    }
    hearts.add("jack");
    hearts.add("queen");
    hearts.add("king");
    hearts.add("ace");

    diamonds.addAll(hearts);
    clubs.addAll(hearts);
    spades.addAll(hearts);

}

// will shuffle your list
public static void main(String[] args) {

    for(int j = 0; j <=10 ; j++) {
        Collections.shuffle(hearts);  // this will do the magic

        System.out.println("List shuffled: ");      
        for(String i : hearts) 
            System.out.println(i + " ");  
    }

}

希望这有帮助,玩得开心!