Eman Hamed
Eman Hamed

Reputation: 29

Error in handling exception for duplicate cards in the Pokerhand game ..

I'm trying to check for the duplicate cards in the poker hand game and throw an exception when it happens. I don't know what's the problem with the code. When I test using the Junit test.. it fails ! I don't know why ! The error says : java.lang.Exception: Unexpected exception, expected but was Any help !

// this is a class that creates the Duplicate Card Exception

public class DuplicateCardException extends RuntimeException{

    public DuplicateCardException(String string) {
        super(string);
    }

}

// This is the poker hand class that checks when the cards will be duplicate

import java.util.ArrayList;
import java.util.Collections;

public class PokerHand implements Comparable <PokerHand> {

public final int CARDS_NUMBER = 5;
private ArrayList<Card> cards = new ArrayList<Card>();


public PokerHand (Card card1 , Card card2, Card card3, Card card4, Card card5)  {

    cards.add(card1);
    cards.add(card2);
    cards.add(card3);
    cards.add(card4);
    cards.add(card5);
    Collections.sort(cards);
    checkCorrectness();
}

private boolean checkCorrectness() {
    if (cards.size() != CARDS_NUMBER)
        throw new DuplicateCardException("Incorrect number of cards!! ");

    for ( int i=0 ; i< cards.size()-1; i++) {
        for ( int j=i+1 ; j< cards.size(); j++) {
            if (i==j)
                continue;
            if (cards.get(i).equals(cards.get(j)))
            throw new DuplicateCardException("Duplicat card");

        }
    }

    return true;
}

@Override
public int compareTo(PokerHand arg0) {

    return 0;
}

public String toString () {
    return cards.get(0).toString() + " " + cards.get(1) + " " + cards.get(2) + " " + cards.get(3)+ " "+ cards.get(4) ;
}
}

// Here is the test code for this exception but it fails !!!

  @Test(expected = DuplicateCardException.class)
  public void testPair2() {
    PokerHand a = new PokerHand(H3, CA, D4, H6, DA);
    a.toString();
    PokerHand b = new PokerHand(H3, C5, HA, SA, C6);
    System.out.println(a );
    System.out.println(b );

    assertTrue(a.compareTo(b) < 0);
  }

Upvotes: 0

Views: 301

Answers (1)

Ted Bigham
Ted Bigham

Reputation: 4341

It's probably not throwing the expected exception because you aren't giving it any duplicate cards. It's not comparing the hands to each other, just to the other cards in the same hand.

Also the assertion

assertTrue(a.compareTo(b) < 0);

if failing becuase you hard coded compareTo to return 0. That's the exception you're getting.

Upvotes: 2

Related Questions