這是我的學校項目中的撲克遊戲。我有一些例外,我無法弄清楚。是什麼給我這個錯誤?
在開始時,我定義了卡類。
class Card {
/* constant suits and ranks */
static final String[] Suit = {"Clubs", "Diamonds", "Hearts", "Spades" };
static final String[] Rank = {"","A","2","3","4","5","6","7","8","9","10","J","Q","K"};
/* Data field of a card: rank and suit */
private int cardRank; /* values: 1-13 (see Rank[] above) */
private int cardSuit; /* values: 0-3 (see Suit[] above) */
/* Constructor to create a card */
/* throw MyPlayingCardException if rank or suit is invalid */
public Card(int rank, int suit) throws MyPlayingCardException {
if ((rank < 1) || (rank > 13))
throw new MyPlayingCardException("Invalid rank:"+rank);
else
cardRank = rank;
if ((suit < 0) || (suit > 3))
throw new MyPlayingCardException("Invalid suit:"+suit);
else
cardSuit = suit;
}
/* Accessor and toString */
/* You may impelemnt equals(), but it will not be used */
public int getRank() { return cardRank; }
public int getSuit() { return cardSuit; }
public String toString() { return Rank[cardRank] + " " + Suit[cardSuit]; }
/* Few quick tests here */
public static void main(String args[])
{
try {
Card c1 = new Card(1,3); // A Spades
System.out.println(c1);
c1 = new Card(10,0); // 10 Clubs
System.out.println(c1);
c1 = new Card(10,5); // generate exception here
}
catch (MyPlayingCardException e)
{
System.out.println("MyPlayingCardException: "+e.getMessage());
}
}
}
我創建了這個類的異常。然後,在我的Decks類中,我繼續從Deck構造函數中獲取異常錯誤。
class Decks {
/* this is used to keep track of original n*52 cards */
private List<Card> originalDecks;
/* this starts with n*52 cards deck from original deck */
/* it is used to keep track of remaining cards to deal */
/* see reset(): it resets dealDecks to a full deck */
private List<Card> dealDecks;
/* number of decks in this object */
private int numberDecks;
/**
* Constructor: Creates default one deck of 52 playing cards in originalDecks and
* copy them to dealDecks.
* initialize numberDecks=n
* Note: You need to catch MyPlayingCardException from Card constructor
* Use ArrayList for both originalDecks & dealDecks
*/
public Decks()
{
// implement this method!
ArrayList<Card> originalDecks = new ArrayList<Card>(52);
ArrayList<Card> dealDecks = new ArrayList<Card>(52);
for (int i=0; i<=3; i++) {
for (int j=0; j<= 13; j++) {
Card card = new Card(j,i);
originalDecks.add(card);
}
}
dealDecks.addAll(originalDecks);
}
爲什麼?如果我使用我的實例卡是從for循環(這意味着他們我< 3,j < 13),爲什麼我仍然得到異常錯誤?
unreported exception MyPlayingCardException; must be caught or declared to be thrown
Card card = new Card(j,i);
Paul,你是說如果我在Card()中拋出異常,它不會進入內存,我必須在下面的類中再次拋出/捕獲它? – 2014-12-04 23:07:58
你必須捕捉並拋出它可能發生的調用路徑的任何地方(除非它是RuntimeException)。 – PaulProgrammer 2014-12-04 23:16:43
我將代碼卡card = new Card(j,i)替換爲try ... catch,如下所示:try {card card = new Card(j,i); } catchcatch(MyPlayingCardException e){System.out.println(「MyPlayingCardException:」+ e.getMessage());},但它給我錯誤後面的線。我在這裏犯了什麼錯誤? – 2014-12-04 23:24:23