0

Here, "cards" is the array of objects, and tcard (a jack of Diamonds), which should exist in the array, is the card I need to search. However the function always returns a value of -1.

public class Card 
{
    private int rank;
    private int suit;
    public static Card[] cards;
    public Card(int rank, int suit) 
    {
        this.rank = rank;
        this.suit = suit;
    }
    public String toString() {
        String[] ranks = {null, "Ace", "2", "3", "4", "5", "6",
                   "7", "8", "9", "10", "Jack", "Queen", "King"};
        String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
        String s = ranks[this.rank] + " of " + suits[this.suit];
        return s;
    }
    public static void createDeck()
    {
        cards=new Card[52];
        int in1=0;
        for (int s1 = 0; s1<= 3; s1++) {
            for (int r1 = 1; r1<= 13; r1++) {
                cards[in1] = new Card(r1, s1);
                in1++;
            }
        }
    }
    public static int search(Card[] scards, Card target) {
        for (int i = 0; i < scards.length; i++) {
            if (scards[i].equals(target)) {
                return i;
            }
        }
        return -1;
    }
    
    public static void main(String args[])
    {
        createDeck();
        Card tcard=new Card(11,1);
        int n1=search(cards,tcard);
        System.out.println(n1);
    }
}
  • 3
    You're calling `scards[i].equals(target)`, but the `Card` you've passed in is a new instance. You're not overriding `equals`, which means it will use reference identity by default (in other words, checking whether the two references are to the same object). You almost certainly want to override `equals` and `hashCode`. – Jon Skeet Mar 20 '21 at 09:41
  • Oh I see thank you. I made a checkequals() function and used that instead now it works fine. Thanks again! – ObservantMagic Mar 20 '21 at 09:45
  • It would be much better to override `equals` instead - that's the method *designed* to check for object equality, which would allow you to use `Card` within maps etc. (You do need to override `hashCode` at the same time though.) – Jon Skeet Mar 20 '21 at 09:54

0 Answers0