I am writing a code that finds what cards the user gets. Returns if its a RoyalFlush.

I have some code that finds the RoyalFlush but its not working as intended.

This is my code;

{
    private Card [] hand;        // the hand of 5 cards

    // the default constructor
    public PokerHand ()
    {
        hand = new Card [5];
    }

    // A constructor to help with testing
    public PokerHand (Card c0, Card c1, Card c2, Card c3, Card c4)
    {
        hand = new Card [5];
        hand[0] = c0;
        hand[1] = c1;
        hand[2] = c2;
        hand[3] = c3;
        hand[4] = c4;
    }

    // This methods fills the hand with cards from the deck.
    // It uses an insertion sort so that the cards are ordered by rank.
    public void fillHand (Deck deck)
    {
        for (int i=0; i<5; i++)
        {
            int j=i-1;
            Card temp = deck.dealCard();
            while (j>=0 && hand[j].getRank() > temp.getRank())
            {   
                hand[j+1] = hand[j];
                j--;
            }
            hand[j+1] = temp;
        }
    }

    // PLACE ADDITIONAL METHODS AFTER THIS COMMENT
    public boolean isRoyalFlush()
    {
        boolean royalFlush = false;
        // simplify the name of hand
        Card c0 = hand[0];
        Card c1 = hand[1];
        Card c2 = hand[2];
        Card c3 = hand[3];
        Card c4 = hand[4];
        // if the five cards in this hand have the same suit, it is flush
        if((c0.getSuit() == c1.getSuit()) && (c1.getSuit() == c2.getSuit())
        && (c2.getSuit() == c3.getSuit()) && (c3.getSuit() == c4.getSuit()))
        {
            // if the five cards in this hand consists of ace, king, queen, jack 
            // and ten, it is royal
            if((c0.getRank() == 10) && (c1.getRank() == 11) && (c2.getRank() == 12)
            && (c3.getRank() == 13) && (c4.getRank() == 14))
             royalFlush = true;
        }
        return royalFlush;
    }

On another class, I will need to count how many users got RoyalFlush.

if(hand.isRoyalFlush())
                count[0]++;

but the count is always showing 0.

1 Answers

0
Nishant Modi On

Because You have checked specific card with specific rank. You are each card with only one rank. where for royal flush the order could be anything. what you are checking is first card is 10, second is jack and so on. But there could be case where first card is jack second is 10 and so on and it will be a royal flush.

Solution - Sort the list of card based on the rank before your check of royal flush