0

I have two simple classes, Card and CardTester. One of the methods in Card checks to see if two cards are equal to one another.

However, when using calling the method matches() in CardTester, it returns false, when it should return true.

public class Card {
  private String rank;
  private String suit;
  private int val;

  public Card(String cardrank, String cardsuit, int cardval) {
    rank = cardrank;
    suit = cardsuit;
    val = cardval
  }

  public boolean matches(Card a) {
    if (this.val == a.val && this.suit == a.suit && this.val == a.val)    {
      return true;
    } 
    else {
      return false;
    }
  } 

Calling the method in another class:

public static void main(String[] args){
  Card c2 = new Card("king", "clubs", 10);
  Card c3 = new Card("king", "clubs", 10);

  if (c2.equals(c3)) {
    System.out.println("Cards are equal");
  } 
  else {
    System.out.println("Cards aren't equal");
  }

The output ends up being "Cards aren't equal" when it should be "Cards are equal".

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
M_chase
  • 3
  • 2
  • @Eran are you sure? This is not exactly the same. He is comparing class objects not strings – Idos Jan 08 '16 at 19:42
  • @Idos OP complains that `mathces` method doesn't work as expected. `matches` compares two Strings with `==`. (`this.suit == a.suit`) – Eran Jan 08 '16 at 19:44
  • 1
    @Eran well he isn't even using that method... I think the answer given addresses the real problem here... – Idos Jan 08 '16 at 19:44
  • @Idos agreed. The problem is within the `equals()` method that he's calling with overriding it. The strings' comparing issue would have been relevant if he was actually calling `matches()`. – Mohammed Aouf Zouag Jan 08 '16 at 19:51

1 Answers1

2

You have to override the equals() method in your Card class and get rid of matches() (note that you are not using equals() instead of matches() in your main method):

A possible implementation:

@Override
public boolean equals(Object o) {
    if(o == null)
        return false;

    // in case you tried to compare a Card with a Not-a-Card object
    if(!o instanceof Card) 
        return false;

    Card c = (Card) o;

    return rank.equals(c.rank) && suit.equals(c.suit) && val == c.val;
}
Mohammed Aouf Zouag
  • 17,042
  • 4
  • 41
  • 67