質問

I've got a multi-part program (2 java files) that are supposed to do two things:

  1. Make a deck of cards (with shuffle, deal, reset)

  2. Create a poker game (making two decks of cards, other stuff...)

There's a barrier I'm hitting because of this Unhandled exception error, and I'm not even sure where it comes from. Error pictured below, source code below that.

Unhandled Exception Error

.

Playing Card Exception Class

class PlayingCardException extends Exception {

    /* Constructor to create a PlayingCardException object */
    PlayingCardException (){
        super ();
    }

    PlayingCardException ( String reason ){
    super ( reason );
    }
}

.

Deck Class /** class Decks represents : n decks of playing cards * Use class Card to construct n * 52 playing cards! * * Do not add new data fields! * Do not modify any methods * You may add private methods */

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 n decks (52 cards each deck) of playing cards in
 *              originalDecks and copy them to dealDecks.
 *              initialize numberDecks=n
 * Note: You need to catch PlayingCardException from Card constructor
 *       Use ArrayList for both originalDecks & dealDecks
 * @throws PlayingCardException 
 */
public Decks(int n) throws PlayingCardException
{
    // implement this method!
    this.originalDecks = new ArrayList<Card>();
    this.dealDecks = new ArrayList<Card>();
    int i, j, k;
    numberDecks = n;
    for (k=0;k<n;k++){
        for (i=1;i<14;i++) 
        {
            for(j=0;j<4;j++) 
            {
                Card orcard = new Card(i,j);
                originalDecks.add(orcard);
                dealDecks.add(orcard);
            }
        }
        }
    }
}
役に立ちましたか?

解決

This checked exception is being declared in the constructor for the Decks class.

public Decks(int n) throws PlayingCardException

It is not a good idea to have constructors throw exceptions.

Are you even sure that the code in the constructor will throw this exception?

Try moving this code to another method which can be called in your main code.

他のヒント

The declaration your constructor is making is that PlayingCardException is a checked exception. This means you must catch it.

Since you're trying to use it as a static field, why bother making it a checked exception at all? Have that extend RuntimeException instead, and if it comes up, you're not absolutely forced to check it any time you want to use it. This way, you can do your static initialization the way you want to.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top