Sam
Sam

Reputation: 93

Comparing Elements Inside an Array

I am having some trouble comparing elements inside an array. I am creating a poker problem and cannot seem to write code to tell if two elements are the same. This is my code comparing what is in the elements

public static boolean pairs() {
    for (int i = currentCard; i < deck.length; i++) {
        for (int j = currentCard ; j < deck.length; j++) {
            if (deck[i] == deck[j])
                return pairs == true;
        }
    }
    return pairs;
}

And this is the code that builds the array:

public CreateDeck() {
    String[] faces = { "Ace", "Deuce", "Three", "Four", "Five", "Six",
        "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" };
    String[] suits = { "Hearts", "Diamonds", "Spades", "Clubs" };

    deck = new Card[NUMBER_OF_CARDS];
    currentCard = 0;

    for (int count = 0; count < deck.length; count++)
        deck[count] = new Card(faces[count % 13], suits[count / 13]);
}

Any help would be appreciated, I have tried many things, and now am just trying things at random. Thanks!

Upvotes: 0

Views: 178

Answers (2)

Burkhard
Burkhard

Reputation: 14738

You need to use and implement Card.equals(Card) instead of ==. (and thus also hashCode(), there are many questions here answering the why).

That would make your pairs() something like this:

public static boolean pairs() {
    {
        for (int i = currentCard; i < deck.length; i++) {
            for (int j = currentCard ; j < deck.length; j++) {
                if (i!=j && deck[i].equals(deck[j]))
                    return true;
            }

        }
    }
    return false;
}

It returns true if and only if the is one deck[i] equals to another deck[j]. false otherwise.

Upvotes: 4

eldris
eldris

Reputation: 205

Right, so the items in your deck array are different Card objects. the == operator compares pointers, so they are different for different objects. If you are trying to compare the values of the Card objects, you need to implements an equals method (overriding the one inherited from Object) and the call deck[i].equals(deck[j]).

Upvotes: 0

Related Questions