java - 使用相等性从 ArrayList 中删除对象

标签 java arraylist

如果两个值彼此相等,我试图从一副牌中删除一张牌。相等性是检测两个值是否匹配(在代码中解释),但我不知道如何删除数组中倒数第二张卡(如果匹配)。

    private void makeMovePreviousPile(){
    int lastDealtCardPos = theFlop.size() - 1; //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 lastDealtCardValue = theFlop.get(lastDealtCardPos).getValue(); // fetches the value of the last dealt card
        String lastDealtCardSuit = theFlop.get(lastDealtCardPos).getSuit(); // fetches the suit of the last dealt card
        String previouslyDealtCardValue = theFlop.get(previouslyDealtCardPos).getValue(); // fetches the 2nd to last dealt card's value
        String previouslyDealtCardSuit = theFlop.get(previouslyDealtCardPos).getSuit(); // fetches the 2nd to last dealt card's suit

        if(lastDealtCardValue.equals(previouslyDealtCardValue)){
            theFlop.remove(previouslyDealtCardValue);
        }
        else if(lastDealtCardSuit.equals(previouslyDealtCardSuit)) {
            theFlop.remove(previouslyDealtCardSuit);
        }
        else {
            System.out.println("Cannot make a move. Are you sure you know the rules?");
        }
        printCardsFromFlop();
        //System.out.print(lastDealtCardValue + "\n");
    }
    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);
}

此方法通过 .equals 检查一张牌的两个特征之一是否可以匹配(2 种花色相同或两者之间的数字相同)。如果它们匹配,则 theFlop.remove(previouslyDealtCard) 应该从数组中完全删除该牌,并且最近发出的牌占据其在数组中的位置。

任何人都可以提供一些关于我应该如何删除匹配卡的指导吗?

谢谢!

最佳答案

显然是 Collection theFlop类似于 List<Card> ,删除 String总是返回 false。 尝试一下

final Card lastDealtCard = theFlop.get(lastDealtCardPos);
...
if (lastDealtCard.getValue().equals(previouslyDealtCard.getValue())) {
    theFlop.remove(previouslyDealtCard);
}

关于java - 使用相等性从 ArrayList 中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30089173/

相关文章:

arrays - 如何从数组中生成单个随机项而不重复?

java - 如何更改继承类中的集合类型?

java - 对二维数组中的对象使用方法

java - requestDispatcher.forward() 不打开新的html页面

java - 如何创建在构造函数中返回给定参数的 ArrayList 的方法?

java - 如何从另一个类中的 ArrayList 获取项目并在当前类的 ArrayList 中引用它(仅使用索引)?

java - Scala/Play/REPL : Configuration error (play. api.libs.Crypto)

java - 聊天机器人从错误的响应数组中返回

java - java.util.Arrays 中的私有(private)静态类 ArrayList - 为什么?

Java - 从数组列表和 JFrame 中删除我的 'worm'