【问题标题】:How to create 4 ArrayList Objects from 1 using iterators (for each)如何使用迭代器从 1 个创建 4 个 ArrayList 对象(每个)
【发布时间】:2015-03-11 23:55:13
【问题描述】:

我基本上有一副 52 张牌,想知道如何将牌发给 4 手牌。 例如,如果这是一场真正的纸牌游戏并且每个玩家都有一手牌,那么他们的手牌将有 52/4 (13) 张牌。

我已经创建了牌组和手牌类并生成了构造函数,因此它们被正确初始化,但是我将如何使用迭代器将每张牌依次处理给每手牌

我查看了迭代器,但找不到合适的应用程序

下面是deck和hand类的构造函数

private ArrayList<Card> deck;

    public Deck() {
        deck = new ArrayList<>(52);
        for (int i = 0; i < 52; i++)
            deck.add(new Card(value, suit);
    }

private ArrayList<Card> hand;

    public Hand() {
        hand = new ArrayList<>();
    }

【问题讨论】:

  • 发布你的代码。

标签: java arraylist iterator playing-cards


【解决方案1】:

我认为您不需要迭代。你可以使用subList

Collections.shuffle(deck);
List<Card> hand1 = deck.subList(0, 13);
List<Card> hand2 = deck.subList(13, 26);
List<Card> hand3 = deck.subList(26, 39);
List<Card> hand4 = deck.subList(39, 52);

这可以概括为返回带有循环的List&lt;List&lt;Card&gt;&gt; 的方法。

【讨论】:

  • 这是非常危险的。我会改用new ArrayList&lt;Card&gt;(deck.subList(0, 13));。否则像hand1.remove(0); System.out.println(hand2); 这样看起来很无辜的代码会抛出ConcurrentModificationException
【解决方案2】:
int cards = 52;
int players = 4;
int hand = new int[players][cards];


int curPlayer = 0;
round = 0;
while(cards != 0){ 
  hand[curPlayer][round] = GetCardFromDeck();
  if(curPlayer == players){
    curPlayer = 0;
  }
  cards--;
  round++;
}

【讨论】:

  • 如果你这样做,是不是更OO一点?
  • 是的,但我不知道他的对象结构。我只是想给他一个逻辑。
【解决方案3】:

如果您必须使用 Iterator 执行此操作,一种方法是:

    List<Card> deck = new ArrayList<Card>(); //populate your deck here
    Collections.shuffle(deck);
    Iterator<Card> iter = deck.iterator();

    List<Card> hand1 = new ArrayList<Card>();
    List<Card> hand2 = new ArrayList<Card>();
    List<Card> hand3 = new ArrayList<Card>();
    List<Card> hand4 = new ArrayList<Card>();

    Card c = null;
    while (true) {
        if (iter.hasNext()) {
            c = iter.next();
            hand1.add(c);
        } else {
            break;
        }
        if (iter.hasNext()) {
            c = iter.next();
            hand2.add(c);
        } else {
            break;
        }
        if (iter.hasNext()) {
            c = iter.next();
            hand3.add(c);
        } else {
            break;
        }
        if (iter.hasNext()) {
            c = iter.next();
            hand4.add(c);
        } else {
            break;
        }
    }

【讨论】:

    猜你喜欢
    • 2016-07-24
    • 2019-06-23
    • 1970-01-01
    • 2021-02-01
    • 2015-01-19
    • 1970-01-01
    • 2020-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多