从arraylist中的特定位置获取对象信息?

时间:2015-05-06 18:33:01

标签: java arraylist

我正在尝试获取有关阵列列表中卡片的具体信息。

arraylist中的每个对象都有两个特征:

value // such as ace, 10, jack, 4
suit // diamonds, clubs etc

我有一个arraylist,它持有洗牌的牌组,打印出来(方法正常,这只是为了显示对象):

as qd ts 4s ad 5d jd 2s 3h ac 2c 5c 9h 4d 6c 9c 8d 7h 3d 7d 8s qs jc ks jh 3s 7s td 6d 9d kc 8h 4c 4h 8c 2h qc 6s qh
// etc etc, arraylist holds 52 objects (the cards)

当从洗牌包(上面的洗牌数组)发牌时,它会从洗牌阵列中删除牌并将其移动到牌组阵列,其数量等于内部对象的总数。

上下文的交易方法

private void dealCard(){
    //TODO
    int totalLeftOver = 0; // used to count the cards left in the shuffled-but-not-dealt pack
    Card topCard = shuffledPack.get(0);
    //String dealtCard = topCard.getValue() + topCard.getSuit();
    shuffledPack.remove(0);
    theFlop.add(topCard);
    System.out.print("Cards on the flop: ");
    for(Card dealt : theFlop){
        String definitelyDealt = dealt.getValue() + dealt.getSuit() + " ";
        System.out.print(definitelyDealt);
    }
    System.out.println("\n");
    for(Card card : shuffledPack){ // for loop to count how cards haven't been dealt
        totalLeftOver++;
    }
    System.out.println("Total number of cards not dealt: " + totalLeftOver); // show how many cards haven't been dealt to the player
}

我现在正在尝试获取触发器阵列列表中特定卡的值和值,具体取决于位置。为简单起见,我想说我想得到最后一张卡的信息。这是我目前拥有的,它可以检测翻牌的大小:

private void makeMovePreviousPile(){
    int lastDealtCardPos = theFlop.size(); //allows us to see how many cards have been dealt, are you even trying to challenge us Chris?
    int previouslyDealtCardPos = lastDealtCardPos - 1;

    if(lastDealtCardPos != 0){ // check that the deck has been shuffled
        String lastCardDealt = lastDealtCardPos.getValue() + lastDealtCardPos.getSuit(); // this doesn't work, its where I'm stuck.
    }
    else { // if it hasn't been shuffled we shun the user.
        System.out.println("Are you sure you shuffled the deck before dealing? Stop trying to cheat.");
        System.out.println("Next time we play Monopoly you won't be the banker. \n");
    }
    //System.out.print(totalDealtCards + " "); // should be equal to the amount of cards we've dealt, if not we've got a problem Huston.
    //System.out.print("Total cards on the flop: " + lastDealtCardPos + " "); // checking to see that its working as intended
    //System.out.print("Previous card dealt: " + previouslyDealtCardPos);
}

现在我们知道了翻牌的大小(已经发出了多少张牌)以及阵列中最后一张牌的位置(在这个例子中是lastDealtCardPos),然后我们如何获取该牌的信息(比如这个位置的“心灵王牌”啊)

以前,当循环打包并在每张卡添加到阵列时打印出来时,我已经使用了这两种方法(可行):

    public  String getSuit() {
    return suit;
}

    public  String getValue() {
    return value;
}

1 个答案:

答案 0 :(得分:1)

好吧,假设翻牌确实是一个ArrayList而不是一个数组(你的问题标题和正文矛盾),你总是可以做到

theFlop.get(lastDealtCardPos).getSuit();
theFlop.get(lastDealtCardPos).getValue();

虽然根据您的代码,您应该记住size()没有编入索引。因此,您应将lastDealtCardPos设置为size()-1