我正在尝试检查扑克牌游戏中的重复牌,并在发生时抛出异常。我不知道代码有什么问题。当我使用Junit测试进行测试时...它失败了!我不知道为什么!错误说:java.lang.Exception:意外的异常,预期但是 任何帮助!
//这是一个创建复制卡例外的类
public class DuplicateCardException extends RuntimeException{
public DuplicateCardException(String string) {
super(string);
}
}
//这是扑克牌级,用于检查卡片何时复制
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) ;
}
}
//这是此异常的测试代码但它失败了!
@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);
}
答案 0 :(得分:2)
它可能不会抛出预期的异常,因为你没有给它任何重复的卡片。它并不是将手彼此比较,而只是用同一只手中的其他牌进行比较。
也是断言
assertTrue(a.compareTo(b) < 0);
如果失败,因为你硬编码compareTo返回0.这是你得到的例外。