Link to home
Start Free TrialLog in
Avatar of ryanbecker24
ryanbecker24

asked on

How do I throw a exception while validating numbers?

Hi,

I am very new to exceptions.

import java.util.ArrayList;
/**
 * Abstract class Participant - write a description of the class here
 * 
 * @author Ryan Becker
 * @version (version number or date here)
 */
public abstract class Participant extends Deck
{
    // instance variables - replace the example below with your own
    protected ArrayList<Participant> participantName;
    protected static double participantNumber;
    protected static double availableFunds;
    protected static double moneyWon;
    protected static double moneyLost;
  
    /**
     * Sets the participant’s name to “Participant-< Participant Number>”
     * Instantiates object of class Hand 
     * Sets Available Funds to $10,000
     * Sets Money Won Statistic  and Money Lost Statistic  to 0
     * Increments instance variable Participant Number  by 1 
    */
    public Participant()
    {
        availableFunds = 10000;
        moneyWon = 0;
        moneyLost = 0;
        participantNumber = 0;
        deck = new ArrayList<Card>();
        participantNumber++;
        
    }
    
    /**
     * Class Constructor which takes participant’s name and the initial amount of money available for betting 
     * Sets the player’s name to provided value
     * Instantiates object of class Hand 
     * Validates and then sets Available Funds to provided value. If the value is invalid (i.e., smaller than the minimum amount allowed or larger than the maximum amount
     * allowed) then the method throws an appropriate exception
     * Sets Money Won Statistic  and Money Lost Statistic  to 0
     * Increment instance variable Player Number  by 1 
     */
    public Participant(double availableFunds, ArrayList<Participant> participantNumber)
    {
        if(availableFunds < 10000 && availableFunds > 0){
        this.availableFunds = availableFunds;
        else{
            throw new NumberFormatException();
        }
        moneyWon = 0;
        moneyLost = 0;
        participantNumber++;
    }
}
    /**
     * Validates and then sets Available Funds to provided value. If the value is invalid 
     * (i.e., smaller than the minimum amount allowed or larger than the maximum amount allowed) then the method throws an appropriate exception
     */
    
    /**
     * Get the value of the money you have lost
     */
    public double getMoneyLost()
    {
        return moneyLost;
    }
    
    /**
     * Set the amount of money you have lost
     */
    public void setMoneyLost(double moneyL)
    {
        moneyLost = moneyL;
    }
    
    /**
     * Get the amount of money you have won
     */
    public double getMoneyWon()
    {
        return moneyWon;
    }
    
    /**
     * Set the amount of money you have lost
     */
    public void setMoneyWon(double moneyW)
    {
        moneyWon = moneyW;
    }
    
    /**
     * Set the amount of the available funds
     */
    public void setAvailableFunds(double funds)
    {
        availableFunds = funds;
    }
    
    /**
     * Get the amount of available funds
     */
    public double getAvailableFunds()
    {
        return availableFunds;
    }
    
    /**
     * Get the player name
     */
    public ArrayList<Participant> getPlayerName()
    {
        return participantName;
    }
    
    /**
     * Set the players name
     */
    public void setPlayerName(ArrayList<Participant> name)
    {
        participantName = name;
    }
    
    /**
     * This is a toString() method that returns the 
     */
//     public String toString()
//     {
//         
//     }
    
    /**
     * abstract method that will get the minimum amount of funds that you can have
     */
    public abstract double getMinFundsLimit();
    
    /**
     * abstract method that will get the maximum amount of funds that you can have
     */
    public abstract double getMaxFundsLimit();
}

import java.util.*;

/*
 * Contains information about the BlackJack hand of cards
 */
/**
 *
 * @author: Dr. Hnatyshin
 * @note:   Does not complete a full javadoc spec of comments
 */
public class Hand extends Deck {

    // player's hand of cards
   // private ArrayList<Card> hand;
    private static final Random r = new Random();
    public static final int MAX_HAND_SIZE = 5;
    public static final int MIN_HAND_SIZE = 2;

    // Constructor
    public Hand() {
        //hand = new ArrayList<Card>();
        deck = new ArrayList<Card>();
    }

    // SUPPORTING METHODS
    // Get the number of cards in the hand
    /**public int getSize() {
        return deck.size();
    }

    // Determine if the hand is empty
    

    // Dump all the cards from the hand
    /**public void reset() {
        hand.clear();
    }

    // Determines if the current hand contains given card
    public boolean contains(Card c) {
        return hand.contains(c);
    }

    // Add a card to the hand
    public void addCard(Card c) {
        hand.add(c);
    }

    // ACCESSORS/MUTATORS
    /**
     * Retrieves and removes a random card from the hand.
     * @return a Card object that will be removed from the hand or
     * null if hand is empty.
     */
    public Card retrieveCard() {
        if (!this.isEmpty()) {
            return deck.get(0);
        }
        return null;
    }

    /**
     * Retrieves and removes a card from specified position in the hand.
     * @return a Card object that will be removed from the hand or
     *  null if hand is empty.
     */
    public Card retrieveCard(int i) {

        // Assume that the user counts cards in a hand starting from 1
        if (i > 0 && i <= this.getSize()) {
            return deck.get(i-1);
        }
        return null;
    }

    /**
     * Retrieves but not removes a card from specified position in the hand.
     * The user counts card in the hand from position 1 and not 0
     * @return a Card object from the deck array.If no object is available in
     *  specified position then returns null
     */
    public Card getCard(int i) {

        // Check if i is valid
        // if not return null
        if (i < 1 || i > this.getSize()) {
            return null;
        }

        // Not enough cards in a deck
        if (deck.size() < i) {
            return null;
        }

        // Remove and return a random card from a specified position in a hand
        // Assume that player counts from 1 instead of 0
        return deck.get(i - 1);
    }

    /**
     * Retrieves but not removes a random card from the hand.
     * @return a Card object from the hand or null if the and is empty
     *
    public Card getCard() {
        // Create new deck if current deck is empty
        if (this.getSize() < 1) {
            reset();
        }

        // Remove and return a random card from a hansd
        return hand.get(r.nextInt(hand.size()));
    }


    // BLACK JACK GAME SUPPORTING METHODS

    /**
     * Return an integer value representing the number of points in the hand
     * given to the method.
     * 
     * @param hand An arrayList containing the value of the hand.
     * @return an integer value representing the value of the hand.
     */
    public int computeBlackJackValue() {
        int numberOfAces = 0;
        int valueOfHand = 0;
        Card c;

        for (int i = 0; i < deck.size(); i++) // Increment through the hand
        {
            c = deck.get(i); //Get the card value
            if (c.getRank().equals("Ace")) {
                numberOfAces += 1; // Increment the number of aces in the hand by 1.
            }
            valueOfHand += Card.getCardValue(c); // Get the value of the Hand.
        }

        if ((numberOfAces >= 1) && (valueOfHand < 12)) {
            valueOfHand += 10; // Make an Ace 11 if the hand value is under 12.
        }

        return valueOfHand;
    }

    /*
     * Compare two hands and see who won. Returns a: 1 for first hand won the
     * game, 0 for nobody winning the game (its a push), or -1 the first
     * hand lost the game.
     *
     * @param hand01 The first hand to be compared.
     * @param hand02 The second hand to be compared.
     * @return A 1, 0, or -1 depending on who won the game.
     */
    public int blackJackCompare(Hand h) {
        //Compute hand values
        int thisHandValue = this.computeBlackJackValue();
        int givenHandValue = h.computeBlackJackValue();

        // Draw
        if (thisHandValue == givenHandValue) {
            return 0;
        }

        // First player wins if
        // both hands are <= 21 and first hand greater than second
        // or
        // second hand > 21 and first hand smaller than second
        if ((thisHandValue <= 21 && givenHandValue <= 21 && thisHandValue > givenHandValue)
                || (givenHandValue > 21 && thisHandValue < givenHandValue)) {
            return 1;
        }

        // Otherwise second player won
        return -1;
    }

    // OTHER SUPPORTING METHODS

    /**
     * Display the value of each Card followed by the hand value.
     * 
     * @param hand The hand that will be evaluated and printed.
     */
    public void printHand() {

        System.out.println(this);
    }

    // Return string representation of a string
    @Override
    public String toString() {
        //String result = "[";

        //for (int i = 0; i < hand.size(); i++) {
            //result += hand.get(i).toStringShort();

            /* no space (" ") added after last card
            //if (i != hand.size() - 1) {
                //System.out.print(" ");
           //}
        //}
        */
        return super.toString() + "] => " + this.computeBlackJackValue();
    }

    // Determines if this given object is the same
    // as the current object
    @Override
    public boolean equals(Object o) {
        if (o == this) {
            return true;
        }

        if (!(o instanceof Hand)) {
            return false;
        }

        Hand h = (Hand) o;
        if (h.getSize() != this.getSize()) {
            return false;
        }

        if (h.getSize() == 0) {
            return true;
        }

        // Check if all the cards in the hands are the same
        // Rememebr that getCard methods counts from 1
        for (int i = 0; i < h.getSize(); i++) {
            if (!this.contains(h.getCard(i+1))) {
                return false;
            }
        }

        return true;
    }

    // Netbeans addded hashCode method
    @Override
    public int hashCode() {
        int hash = 5;
        hash = 97 * hash + (this.deck != null ? this.deck.hashCode() : 0);
        return hash;
    }
}
mport java.util.*;

/*
 * Contains information about the BlackJack hand of cards
 */
/**
 *
 * @author: Dr. Hnatyshin
 * @note:   Does not complete a full javadoc spec of comments
 */
public class Hand extends Deck {

    // player's hand of cards
   // private ArrayList<Card> hand;
    private static final Random r = new Random();
    public static final int MAX_HAND_SIZE = 5;
    public static final int MIN_HAND_SIZE = 2;

    // Constructor
    public Hand() {
        //hand = new ArrayList<Card>();
        deck = new ArrayList<Card>();
    }

    // SUPPORTING METHODS
    // Get the number of cards in the hand
    /**public int getSize() {
        return deck.size();
    }

    // Determine if the hand is empty
    

    // Dump all the cards from the hand
    /**public void reset() {
        hand.clear();
    }

    // Determines if the current hand contains given card
    public boolean contains(Card c) {
        return hand.contains(c);
    }

    // Add a card to the hand
    public void addCard(Card c) {
        hand.add(c);
    }

    // ACCESSORS/MUTATORS
    /**
     * Retrieves and removes a random card from the hand.
     * @return a Card object that will be removed from the hand or
     * null if hand is empty.
     */
    public Card retrieveCard() {
        if (!this.isEmpty()) {
            return deck.get(0);
        }
        return null;
    }

    /**
     * Retrieves and removes a card from specified position in the hand.
     * @return a Card object that will be removed from the hand or
     *  null if hand is empty.
     */
    public Card retrieveCard(int i) {

        // Assume that the user counts cards in a hand starting from 1
        if (i > 0 && i <= this.getSize()) {
            return deck.get(i-1);
        }
        return null;
    }

    /**
     * Retrieves but not removes a card from specified position in the hand.
     * The user counts card in the hand from position 1 and not 0
     * @return a Card object from the deck array.If no object is available in
     *  specified position then returns null
     */
    public Card getCard(int i) {

        // Check if i is valid
        // if not return null
        if (i < 1 || i > this.getSize()) {
            return null;
        }

        // Not enough cards in a deck
        if (deck.size() < i) {
            return null;
        }

        // Remove and return a random card from a specified position in a hand
        // Assume that player counts from 1 instead of 0
        return deck.get(i - 1);
    }

    /**
     * Retrieves but not removes a random card from the hand.
     * @return a Card object from the hand or null if the and is empty
     *
    public Card getCard() {
        // Create new deck if current deck is empty
        if (this.getSize() < 1) {
            reset();
        }

        // Remove and return a random card from a hansd
        return hand.get(r.nextInt(hand.size()));
    }


    // BLACK JACK GAME SUPPORTING METHODS

    /**
     * Return an integer value representing the number of points in the hand
     * given to the method.
     * 
     * @param hand An arrayList containing the value of the hand.
     * @return an integer value representing the value of the hand.
     */
    public int computeBlackJackValue() {
        int numberOfAces = 0;
        int valueOfHand = 0;
        Card c;

        for (int i = 0; i < deck.size(); i++) // Increment through the hand
        {
            c = deck.get(i); //Get the card value
            if (c.getRank().equals("Ace")) {
                numberOfAces += 1; // Increment the number of aces in the hand by 1.
            }
            valueOfHand += Card.getCardValue(c); // Get the value of the Hand.
        }

        if ((numberOfAces >= 1) && (valueOfHand < 12)) {
            valueOfHand += 10; // Make an Ace 11 if the hand value is under 12.
        }

        return valueOfHand;
    }

    /*
     * Compare two hands and see who won. Returns a: 1 for first hand won the
     * game, 0 for nobody winning the game (its a push), or -1 the first
     * hand lost the game.
     *
     * @param hand01 The first hand to be compared.
     * @param hand02 The second hand to be compared.
     * @return A 1, 0, or -1 depending on who won the game.
     */
    public int blackJackCompare(Hand h) {
        //Compute hand values
        int thisHandValue = this.computeBlackJackValue();
        int givenHandValue = h.computeBlackJackValue();

        // Draw
        if (thisHandValue == givenHandValue) {
            return 0;
        }

        // First player wins if
        // both hands are <= 21 and first hand greater than second
        // or
        // second hand > 21 and first hand smaller than second
        if ((thisHandValue <= 21 && givenHandValue <= 21 && thisHandValue > givenHandValue)
                || (givenHandValue > 21 && thisHandValue < givenHandValue)) {
            return 1;
        }

        // Otherwise second player won
        return -1;
    }

    // OTHER SUPPORTING METHODS

    /**
     * Display the value of each Card followed by the hand value.
     * 
     * @param hand The hand that will be evaluated and printed.
     */
    public void printHand() {

        System.out.println(this);
    }

    // Return string representation of a string
    @Override
    public String toString() {
        //String result = "[";

        //for (int i = 0; i < hand.size(); i++) {
            //result += hand.get(i).toStringShort();

            /* no space (" ") added after last card
            //if (i != hand.size() - 1) {
                //System.out.print(" ");
           //}
        //}
        */
        return super.toString() + "] => " + this.computeBlackJackValue();
    }

    // Determines if this given object is the same
    // as the current object
    @Override
    public boolean equals(Object o) {
        if (o == this) {
            return true;
        }

        if (!(o instanceof Hand)) {
            return false;
        }

        Hand h = (Hand) o;
        if (h.getSize() != this.getSize()) {
            return false;
        }

        if (h.getSize() == 0) {
            return true;
        }

        // Check if all the cards in the hands are the same
        // Rememebr that getCard methods counts from 1
        for (int i = 0; i < h.getSize(); i++) {
            if (!this.contains(h.getCard(i+1))) {
                return false;
            }
        }

        return true;
    }

    // Netbeans addded hashCode method
    @Override
    public int hashCode() {
        int hash = 5;
        hash = 97 * hash + (this.deck != null ? this.deck.hashCode() : 0);
        return hash;
    }
}

Open in new window

Avatar of for_yan
for_yan
Flag of United States of America image

You don't want to call this
if(availableFunds < 10000 && availableFunds > 0){
        this.availableFunds = availableFunds;
        else{
            throw new NumberFormatException();
        }

Open in new window


NumberFormatException

because this name is used in standard libarary


You rather write your own class
public class InvalidFundsException extends Exception {
String message;

public InvalidFundsException (String message) {
this.message = message;
}

public String toString() {
return message;

}



}

Open in new window


And for the rest of it it iis correct you can throe exception in this way:

if(availableFunds < 10000 && availableFunds > 0){
        this.availableFunds = availableFunds;
        else{
            throw new InvalidFundsException(" You need to have fuunds between 0 and 10000 to partiicipate in the game");
        }

Open in new window




I guess, I picked the right piece of the code related to execption.

I was not able to compile your code, as the code you posted contains class Hand twice, but does not contain class Deck

Avatar of ryanbecker24
ryanbecker24

ASKER


Here is the deck class

 mport java.util.*;

/*
 * Contains information about the BlackJack hand of cards
 */
/**
 *
 * @author: Dr. Hnatyshin
 * @note:   Does not complete a full javadoc spec of comments
 */
public class Hand extends Deck {

    // player's hand of cards
   // private ArrayList<Card> hand;
    private static final Random r = new Random();
    public static final int MAX_HAND_SIZE = 5;
    public static final int MIN_HAND_SIZE = 2;

    // Constructor
    public Hand() {
        //hand = new ArrayList<Card>();
        deck = new ArrayList<Card>();
    }

    // SUPPORTING METHODS
    // Get the number of cards in the hand
    /**public int getSize() {
        return deck.size();
    }

    // Determine if the hand is empty
    

    // Dump all the cards from the hand
    /**public void reset() {
        hand.clear();
    }

    // Determines if the current hand contains given card
    public boolean contains(Card c) {
        return hand.contains(c);
    }

    // Add a card to the hand
    public void addCard(Card c) {
        hand.add(c);
    }

    // ACCESSORS/MUTATORS
    /**
     * Retrieves and removes a random card from the hand.
     * @return a Card object that will be removed from the hand or
     * null if hand is empty.
     */
    public Card retrieveCard() {
        if (!this.isEmpty()) {
            return deck.get(0);
        }
        return null;
    }

    /**
     * Retrieves and removes a card from specified position in the hand.
     * @return a Card object that will be removed from the hand or
     *  null if hand is empty.
     */
    public Card retrieveCard(int i) {

        // Assume that the user counts cards in a hand starting from 1
        if (i > 0 && i <= this.getSize()) {
            return deck.get(i-1);
        }
        return null;
    }

    /**
     * Retrieves but not removes a card from specified position in the hand.
     * The user counts card in the hand from position 1 and not 0
     * @return a Card object from the deck array.If no object is available in
     *  specified position then returns null
     */
    public Card getCard(int i) {

        // Check if i is valid
        // if not return null
        if (i < 1 || i > this.getSize()) {
            return null;
        }

        // Not enough cards in a deck
        if (deck.size() < i) {
            return null;
        }

        // Remove and return a random card from a specified position in a hand
        // Assume that player counts from 1 instead of 0
        return deck.get(i - 1);
    }

    /**
     * Retrieves but not removes a random card from the hand.
     * @return a Card object from the hand or null if the and is empty
     *
    public Card getCard() {
        // Create new deck if current deck is empty
        if (this.getSize() < 1) {
            reset();
        }

        // Remove and return a random card from a hansd
        return hand.get(r.nextInt(hand.size()));
    }


    // BLACK JACK GAME SUPPORTING METHODS

    /**
     * Return an integer value representing the number of points in the hand
     * given to the method.
     * 
     * @param hand An arrayList containing the value of the hand.
     * @return an integer value representing the value of the hand.
     */
    public int computeBlackJackValue() {
        int numberOfAces = 0;
        int valueOfHand = 0;
        Card c;

        for (int i = 0; i < deck.size(); i++) // Increment through the hand
        {
            c = deck.get(i); //Get the card value
            if (c.getRank().equals("Ace")) {
                numberOfAces += 1; // Increment the number of aces in the hand by 1.
            }
            valueOfHand += Card.getCardValue(c); // Get the value of the Hand.
        }

        if ((numberOfAces >= 1) && (valueOfHand < 12)) {
            valueOfHand += 10; // Make an Ace 11 if the hand value is under 12.
        }

        return valueOfHand;
    }

    /*
     * Compare two hands and see who won. Returns a: 1 for first hand won the
     * game, 0 for nobody winning the game (its a push), or -1 the first
     * hand lost the game.
     *
     * @param hand01 The first hand to be compared.
     * @param hand02 The second hand to be compared.
     * @return A 1, 0, or -1 depending on who won the game.
     */
    public int blackJackCompare(Hand h) {
        //Compute hand values
        int thisHandValue = this.computeBlackJackValue();
        int givenHandValue = h.computeBlackJackValue();

        // Draw
        if (thisHandValue == givenHandValue) {
            return 0;
        }

        // First player wins if
        // both hands are <= 21 and first hand greater than second
        // or
        // second hand > 21 and first hand smaller than second
        if ((thisHandValue <= 21 && givenHandValue <= 21 && thisHandValue > givenHandValue)
                || (givenHandValue > 21 && thisHandValue < givenHandValue)) {
            return 1;
        }

        // Otherwise second player won
        return -1;
    }

    // OTHER SUPPORTING METHODS

    /**
     * Display the value of each Card followed by the hand value.
     * 
     * @param hand The hand that will be evaluated and printed.
     */
    public void printHand() {

        System.out.println(this);
    }

    // Return string representation of a string
    @Override
    public String toString() {
        //String result = "[";

        //for (int i = 0; i < hand.size(); i++) {
            //result += hand.get(i).toStringShort();

            /* no space (" ") added after last card
            //if (i != hand.size() - 1) {
                //System.out.print(" ");
           //}
        //}
        */
        return super.toString() + "] => " + this.computeBlackJackValue();
    }

    // Determines if this given object is the same
    // as the current object
    @Override
    public boolean equals(Object o) {
        if (o == this) {
            return true;
        }

        if (!(o instanceof Hand)) {
            return false;
        }

        Hand h = (Hand) o;
        if (h.getSize() != this.getSize()) {
            return false;
        }

        if (h.getSize() == 0) {
            return true;
        }

        // Check if all the cards in the hands are the same
        // Rememebr that getCard methods counts from 1
        for (int i = 0; i < h.getSize(); i++) {
            if (!this.contains(h.getCard(i+1))) {
                return false;
            }
        }

        return true;
    }

    // Netbeans addded hashCode method
    @Override
    public int hashCode() {
        int hash = 5;
        hash = 97 * hash + (this.deck != null ? this.deck.hashCode() : 0);
        return hash;
    }
}

Open in new window

No this again Hand (not Deck)

But I don't think I need them - it will probably not affect the issue related to Exceptions
Also, am I supposed to write public class InvalidFundsException extends Exception inside of the Participant class and the rest of the methods. The if statements still go in the constructor right?
No I suggest to write it as a reagular  class (not inner class), so it should be outside of any class, just regular class in its own right.
The if statements and the actual throwing would of course be in your Participant class or in any other classes of your program where
you may need to throw such exception
What I don't like in your code, at least in the pieces which I see - and it has nothing to do with your question about exceptions -
is that it jsust has

Participant extends Deck - seems really strange and hard to assign any practical logic to that

Keep in mind that "extends" is an IS-A relationsship. So if you replace, it will say Participant IS A Deck - sounds really weird
Your program may function fine with all that but in a sense of understanding of how it functions - it probably would not be an easy task.

I would try to re-design it. If there could be a field of type Deck in class Participant - that would be reasonable, like
Participant HAS A Deck - that may be comprehensible (again I didn' t go into details of your coding - just form the naming point of view)
but this is really something which in general may make sense, as opposed to Participant IS A Deck


Sorry about that.


import java.util.ArrayList;
import java.util.Random;

/**
 * This class creates a deck of card out of 52 of the card objects created.
 * 
 * @author Bradley Ebinger
 * @version 1.00
 *
 * @updated by Dr. VH
 */
public class Deck {

    private ArrayList<Card> deck;
    private static final Random r = new Random();
    private static final int DECK_SIZE = 52;

    /**
     * Default Constructor. Creates a deck of 52 Cards.
     */
    public Deck() {
        deck = new ArrayList<Card>(DECK_SIZE);
        createNewDeck();
    }

    /**
     * Resets the current deck of cards to the new deck of 52 cards.
     */
    private void createNewDeck() {
        String[] ranks = Card.getPossibleRanks();
        char[] suits = Card.getPossibleSuits();

        deck.clear();// Clear the arraylist of all objects.

        // Go through all possible combinations of suits and ranks
        // For each combination create a card and add it into a deck
        for (int i = 0; i < suits.length; i++) {
            for (int j = 0; j < ranks.length; j++) {
                deck.add(new Card(ranks[j], suits[i]));
            }
        }
    }

    // SUPPORTING METHODS
    /**
     * Resets the current deck of cards to the default deck of cards.
     */
    public void reset() {
        deck.clear();
    }

    // Get the number of cards in the hand
    public int getSize() {
        return deck.size();
    }

    // Determine if the deck of card is empty
    public boolean isEmpty() {
        return this.getSize() == 0;
    }

    // Determines if the current hand contains given card
    public boolean contains(Card c) {
        return deck.contains(c);
    }

// ACCESSOR/MUTATORS
    /**
     * Retrieves and removes a random card from the deck.
     * @return a Card object that will be removed from the deck array. If the
     * deck is empty, it will reset the deck of cards to 52.
     */
    public Card retrieveCard() {
        // Create new deck if current deck is empty
        if (deck.size() < 1) {
            reset();
        }

        // Remove and return a random card from a deck
        return deck.remove(r.nextInt(deck.size()));
    }

    /**
     * Retrieves and removes a card from specified position in the deck.
     * @return a Card object that will be removed from the deck array. If the
     * deck is empty, it will reset the deck of cards to 52.
     */
    public Card retrieveCard(int i) {

        // Check if i is valid
        // if not return null
        if (i <= 0 || i > DECK_SIZE) {
            return null;
        }

        // Not enough cards in a deck
        if (deck.size() < i) {
            return null;
        }

        // Remove and return a random card from a deck
        // Assume that player counts from 1 instead of 0
        return deck.remove(i - 1);
    }

    /**
     * Retrieves but not removes a random card from n the deck.
     * @return a Card object from the deck or null if the deck is empty
     */
    public Card getCard() {
        // Create new deck if current deck is empty
        if (deck.size() < 1) {
            reset();
        }

        // Remove and return a random card from a deck
        return deck.get(r.nextInt(deck.size()));
    }

    /**
     * Retrieves but not removes a card from specified position in the deck.
     * @return a Card object from the deck array.If no object is available in
     *  specified position then returns null
     */
    public Card getCard(int i) {

        // Check if i is valid
        // if not return null
        if (i <= 0 || i > DECK_SIZE) {
            return null;
        }

        // Not enough cards in a deck
        if (deck.size() < i) {
            return null;
        }

        // Remove and return a card from specified position in a deck
        // Assume that player counts from 1 instead of 0
        return deck.remove(i - 1);
    }

    /**
     * Returns an ArrayList of card objects of a specified size.
     * If the size is invalid (i.e. size <= 0), the method will return an empty ArrayList.
     * 
     * @param size The size of the hand to be returned.
     * @return An arrayList of Card objects of the specified size
     */
    public ArrayList<Card> getHand(int size) {
        ArrayList<Card> handOfCards = new ArrayList<Card>(size);

        // REmove from the deck specified number of cards and add them into a
        // ArrayList which specifies a hand of cards
        for (int i = 0; i < size; i++) {
            handOfCards.add(retrieveCard());
        }

        return handOfCards;
    }



    // Return string representation of a string
    @Override
    public String toString() {
        String result = "[";

        for (int i = 0; i < deck.size(); i++) {
            result += deck.get(i).toStringShort();

            // no space (" ") added after last card
            if (i != deck.size() - 1) {
                System.out.print(" ");
            }
        }

        return result + "]";
    }

    // Determines if this given object is the same
    // as the current object
    @Override
    public boolean equals(Object obj) {
         if (obj == this) {
            return true;
        }

        if (!(obj instanceof Deck)) {
            return false;
        }

        Deck d = (Deck) obj;
        if (d.getSize() != this.getSize()) {
            return false;
        }

        if (d.getSize() == 0) {
            return true;
        }

        // Check if all the cards in the hands are the same
        // Rememebr that getCard methods counts from 1
        for (int i = 0; i < d.getSize(); i++) {
            if (!this.contains(d.getCard(i+1))) {
                return false;
            }
        }

        return true;
    }

    // Netbeans added method
    @Override
    public int hashCode() {
        int hash = 3;
        hash = 67 * hash + (this.deck != null ? this.deck.hashCode() : 0);
        return hash;
    }

}

Open in new window

OK. This is indded class Deck.
But I don't think I need it in the context of your question about Exceptions - correct?
I was just fooling around with the deck thing. I need to instantiate an object of class Hand so I just guessed that since Hand extends Deck, I would need to extend Deck.
Well for Hand, Deck, and Card I need to write exceptions but I have no clue where to write them.

This is Card:

 

/**
 * This class provides an implementation of a class that handles one card.
 *
 * @author Bradley Ebinger
 * @version 1.00
 *
 * @updated by Dr. VH
 * @updated by Ryan Becker
 */
public class Card implements Comparable
{

    private String rank; // Card Rank: a number between 2 and 10, or Jack,
    // Queen, King, or Ace.
    private char suit;    // Card Suit: S, C, H, or D (spades, clubs, hearts,
    // or diamonds.)
    // Helpful Supporting Stuctures
   private static String[] Ranks = {"2", "3", "4", "5", "6", "7", "8", "9",
        "10", "Jack", "Queen", "King", "Ace"};
    private static char[] Suits = {'C', 'H', 'D', 'S'};
    
//     public static enum Rank {Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten,Jack,Queen,King,Ace;
//         public static Rank getRank(int i)
//         {
//             switch(i % Rank.values().length)
//             {
//             case 0: return Two;
//             case 1: return Three;
//             case 3: return Four;
//             case 4: return Five;
//             case 5: return Six;
//             case 6: return Seven;
//             case 7: return Eight;
//             case 8: return Nine;
//             case 9: return Ten;
//             case 10: return Jack;
//             case 11: return Queen;
//             case 12: return King;
//             default: return Ace;
//         }
//     }
// };
// 
//     public static enum Suit{Spades,Clubs,Hearts,Diamonds;
//         public static Suit getSuit(int j)
//         {
//             switch(j % Suit.values().length)
//         {
//             case 0: return Spades;
//             case 1: return Clubs;
//             case 2: return Hearts;
//             default: return Diamonds;
//         }
//     }
// };
            
    /**
     * This is the Class Card's Default constructor. Automatically sets 
     * the card rank to "2" and the card suit to 'H' for Hearts.
     */
    public Card() {
        rank = "2"; // Set rank variable to "2"
        suit = 'H'; // Set Suit variable to 'H' 
    }

    /**
     * This is the class Class constructor when the class is instantiated and
     * sets the card rank as well as suit values to values provided.
     * If either of the values provided are invalid, then the given values will
     * be ignored and the Card values will be set to default values, a rank of 2
     * and a suit of Hearts.
     *
     * @param rank The rank the card will be.
     * @param suit The suit the card will be.
     */
    public Card(String rank, char suit) {
        //set to default values
        this.rank = "2";
        this.suit = 'H';

        // If valid then update with passed values
        if ((checkRank(rank)) && (checkSuit(suit))) {
            this.rank = rank;
            this.suit = suit;
        }
    }
    
    /**
     * This compareTo method reads the card and compares to the current card
     * @param Card
     */

//     public int compareTo(Object c)
//     {
//         if(((Card) c).getRank().ordinal < this.getRank())
//         return -1;
//         else if(c.getRank() == getRank())
//         if(c.getSuit() < getSuit())
//         return -1;
//         else if(c.getSuit() == getSuit())
//         if(c.getSuit() < getSuit())
//         return -1;
     public int compareTo(Object  o1) {
         Card o = (Card) o1;
    if (this.suit < o.suit) {
      return -1;
    } else if (this.suit > o.suit) {
      return 1;
    } else {
      // suit is identical: compare number
      if (this.rank.compareTo(o.rank) > 0) {
        return -1;
      } else if (this.rank.compareTo(o.rank) < 0) {
        return 1;
      } else {
        return 0;
      }
    }
  } 

  
        
    /*}
    /**
     * Check the value of the given rank and compare against the string array.
     * If the rank is valid return true. If not, return false.
     *
     * @param rank The string that the program will be checking for validity.
     * @return a boolean that is true of the rank is valid.
     */
    private boolean checkRank(String rank) {
        // Go through all possible ranks until find  match
        // If match is found then rank value is valid
      
            for (int i = 0; i < Ranks.length; i++) {
            if (Ranks[i].equals(rank)) {
                return true;
            }
        }
   

        return false;
    }

    /**
     * Check the value of the given suit and compare against the char array.
     * If the suit is valid return true. If not, return false.
     *
     * @param suit The char that the program will be checking for validity.
     * @return a boolean that is true of the suit is valid.
     */
    private boolean checkSuit(char suit) {
        // Go through all possible suits until find  match
        // If match is found then suit value is valid
        for (int i = 0; i < Suits.length; i++) // Step through the Suits Array.
        {
            if (Suits[i] == suit) {
                return true;
            }
        }

        return false;
    }

    /**
     * This method is an accessor that returns a String representing the
     * Rank of the set Card.
     *
     * @return The rank of the card currently selected.
     */
    public String getRank() {
        return rank;
    }

    /**
     * This method is an accessor that returns a character representing the
     * suit of the set Card.
     * Card Characters: 'C' - Clubs
     *                  'H' - Hearts
     *                  'D' - Diamonds
     *                  'S' - Spades
     *
     * @return A char representing the suit of the card selected.
     */
    public char getSuit() {
        return suit;
    }

    /**
     * Set the rank of the card to a specified string.
     * Format: - Card Number only for any number card from 2 to 10.    Ex: Two = 2
     *         - Card Name (first letter capitalized) for a face card. Ex. "Jack"
     *
     * @param rank String Parameter that changes the rank of the card.
     */
    public void setRank(String rank) {
        if (checkRank(rank)) {
            this.rank = rank;
        }
    }

    /**
     * Set the suit of the card to a specified character.
     * Format: - First letter of the suit(Capital Letter). Ex. "Spades" = 'S'
     *
     * @param suit Character that describes the suit of the Card.
     */
    public void setSuit(char suit) {
        if (checkSuit(suit)) {
            this.suit = suit;
        }
    }

    /**
     * This method returns a String array containing all of the possible card
     * ranks.
     *
     * @return A string array containing all of the possible card ranks.
     */
    public static String[] getPossibleRanks() {
        return Ranks;
    }

    /**
     * This method returns a char array containing all of the possible card
     * suits.
     *
     * @return A character array containing all of the possible card suits.
     */
    public static char[] getPossibleSuits() {
        return Suits;
    }

     /**
     * This method takes an object of class Card and returns an integer value
     * of that card.
     * @param c The card object that will be evaluated.
     * @return An integer value representing the value of the card object.
     */
    public static int getCardValue(Card c) {
        String rankString = c.getRank(); // Get the string value of the rank
        int cardValue = 0; //create an int that will hold the int representation.

        try {
            Integer i = new Integer(rankString); //Create an integer wrapper
            cardValue = i.intValue(); //Turn the value into an int.
        } catch (NumberFormatException e) // If the String can not be turned into
        {                               // an int,
            if (rankString.equals("Ace"))// evaluate it as an Ace.
            {
                cardValue = 1;
            } else {
                cardValue = 10;         //If not, its a Jack, Queen, or King.
            }
        }

        return cardValue;
    }
    
    
     /**
     * This method takes an object of class Card and returns an integer value
     * of that card.
     * @param c The card object that will be evaluated.
     * @return An integer value representing the value of the card object.
     */
    public int getCardValue() {
        return Card.getCardValue(this);
    }
    /**
     * This method returns a string representation if the card 
     * that looks as follows: "2 of Hearts" or "Jack of Spades".
     * 
     * @return a string representation of the card.
     */
    public String toString() {
        String cardName = getRank() + " of "; // Get the Rank of the card first.

        switch (getSuit()) // Get the char value containing the Suit
        {
            case 'C': return cardName + "Clubs";
            case 'H': return cardName + "Hearts";
            case 'S': return cardName + "Spades";
            case 'D': return cardName = "Diamonds";
            default:  return "Invalid Card";
        }
    }

    // Provides a compact string  representation of the card
    public String toStringShort() {
        return "[" + getRank().charAt(0) + "-" + getSuit() + "]";
    }
   
    // Deteremines if given object is the same object of class Card
    @Override
    public boolean equals(Object o)
    {
        if (o == this)
        {
            return true;
        }
        
        if (!(o instanceof Card))
        {
            return false;
        }
        
        Card c = (Card) o;
        return this.getRank().equals(c.getRank()) && 
               this.getSuit() == c.getSuit();
    }

    // Netbeans added method
    @Override
    public int hashCode() {
        int hash = 7;
        hash = 23 * hash + (this.rank != null ? this.rank.hashCode() : 0);
        hash = 23 * hash + this.suit;
        return hash;
    }
}

Open in new window

For the if statement exception it says there is an else without if. Probably a missed bracket that I can't find.

Here is the constructor:

 
 public Participant(double availableFunds, ArrayList<Participant> participantNumber)
    {
        if(availableFunds < 10000 && availableFunds > 0){
        this.availableFunds = availableFunds;
        }
        else{
            throw new InvalidFundsException(" You need to have fuunds between 0 and 10000 to partiicipate in the game");
        } 
    
        moneyWon = 0;
        moneyLost = 0;
        participantNumber++;
    }
}

Open in new window

In this snippet ou have one extra xlosing brace - it is probably not the reason for the error mentionsed
ASKER CERTIFIED SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
It is not difficult to invent exception just to show how to use them, say in the constructor of Card
if suit provides invalid character you can write InvlaidSuitException
this would hardly be useful in real life, but for the sake of excercise would be OK