SophiaPretty

(5)

$14/per page/Negotiable

About SophiaPretty

Levels Tought:
Elementary,Middle School,High School,College,University,PHD

Expertise:
Accounting,Algebra See all
Accounting,Algebra,Applied Sciences,Architecture and Design,Art & Design,Biology,Business & Finance,Calculus,Chemistry,Communications,Computer Science,Economics,Engineering,English,Environmental science,Essay writing Hide all
Teaching Since: Jul 2017
Last Sign in: 313 Weeks Ago, 6 Days Ago
Questions Answered: 15833
Tutorials Posted: 15827

Education

  • MBA,PHD, Juris Doctor
    Strayer,Devery,Harvard University
    Mar-1995 - Mar-2002

Experience

  • Manager Planning
    WalMart
    Mar-2001 - Feb-2009

Category > Computer Science Posted 04 Dec 2017 My Price 10.00

Implementing PlayingCard.java with implementing

I need help Implementing PlayingCard.java. Need help with implementing Decks method and can you check if there's any errors with the code. The correct output should be like the one in Readme.

  • package PJ4;

    import java.util.*;

    //=================================================================================
    /**
     * class PlayingCardException: It is used for errors related to Card and Deck
     * objects Do not modify this class!
     */
    @SuppressWarnings("serial")
    class PlayingCardException extends Exception {

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

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

    // =================================================================================
    /**
     * class Card : for creating playing card objects it is an immutable class. Rank
     * - valid values are 1 to 13 Suit - valid values are 0 to 4 Do not modify this
     * class!
     */
    class Card {

        /* constant suits and ranks */
        static final String[] Suit = { "Joker", "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-4 (see Suit[] above) */

        /* Constructor to create a card */
        /* throw PlayingCardException if rank or suit is invalid */
        public Card(int suit, int rank) throws PlayingCardException {

            // suit =0 is joker, rank must be 1 or 2
            if (suit == 0) {
                if ((rank < 1) || (rank > 2))
                    throw new PlayingCardException("Invalid rank for Joker:" + rank);
                cardRank = rank;
                cardSuit = 0;
            } else {

                if ((rank < 1) || (rank > 13))
                    throw new PlayingCardException("Invalid rank:" + rank);
                else
                    cardRank = rank;

                if ((suit < 1) || (suit > 4))
                    throw new PlayingCardException("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() {
            if (cardSuit == 0)
                return Suit[cardSuit] + " #" + cardRank;
            else
                return Rank[cardRank] + " " + Suit[cardSuit];
        }

        /* Few quick tests here */
        public static void main(String args[]) {
            try {
                Card c1 = new Card(4, 1); // A Spades
                System.out.println(c1);
                c1 = new Card(1, 10); // 10 Clubs
                System.out.println(c1);
                c1 = new Card(0, 2); // Joker #2
                System.out.println(c1);
                c1 = new Card(5, 10); // generate exception here
            } catch (PlayingCardException e) {
                System.out.println("PlayingCardException: " + e.getMessage());
            }
        }
    }

    // =================================================================================
    /**
     * class Decks represents : n decks of 52 (or 54) playing cards Use class Card
     * to construct n * 52 (or 54) 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 or n*54 cards */
        private List<Card> originalDecks;

        /* this starts with copying cards from originalDecks */
        /* it is used to play the card game */
        /* see reset(): resets gameDecks to originalDecks */
        private List<Card> gameDecks;

        /* number of decks in this object */
        private int numberDecks;
        private boolean withJokers;

        /**
         * Constructor: Creates one deck of 52 or 54 (withJokers = false or true)
         * playing cards in originalDecks and copy them to gameDecks. initialize
         * numberDecks=1 Note: You need to catch PlayingCardException from Card
         * constructor Use ArrayList for both originalDecks & gameDecks
         */
        public Decks(boolean withJokers) {
            // implement this method!
            this(1, withJokers);
        }

        /**
         * Constructor: Creates n decks (54 or 52 cards each deck - with or without
         * Jokers) of playing cards in originalDecks and copy them to gameDecks.
         * initialize numberDecks=n Note: You need to catch PlayingCardException
         * from Card constructor Use ArrayList for both originalDecks & gameDecks
         */
        public Decks(int n, boolean withJokers) {
            // implement this method!
            originalDecks = new ArrayList<Card>(numberDecks*52);
            numberDecks = n;
            for (int i = 0; i < numberDecks; i++) {
                for (int suit = 1; suit <= 4; suit++) {
                    for (int rank = 1; rank <= 13; rank++) {
                              Card tempCard;
                        try {
                            tempCard = new Card (suit,rank);
                            originalDecks.add(tempCard);
                        } catch (PlayingCardException e) {
                            System.out.println("PlayingCardException: " + e.getMessage());
                        }

                    }

                }

            }
           
            gameDecks = new ArrayList<>(originalDecks);       
           
           
        }

        /**
         * Task: Shuffles cards in gameDecks. Hint: Look at java.util.Collections
         */
        public void shuffle() {
            // implement this method!
            Collections.shuffle(gameDecks);
        }

        /**
         * Task: Deals cards from the gameDecks.
         *
         * @param numberCards
         *            number of cards to deal
         * @return a list containing cards that were dealt
         * @throw PlayingCardException if numberCard > number of remaining cards
         *
         *        Note: You need to create ArrayList to stored dealt cards and
         *        should removed dealt cards from gameDecks
         *
         */
        public List<Card> deal(int numberCards) throws PlayingCardException {
            // implement this method!
            List<Card>dealtCards = new ArrayList<>();
            if(numberCards > dealtCards.size()){
                throw new PlayingCardException(": Not enough cards left to deal.");
            }
            for(int i = 0; i<numberCards;i++ ){
                dealtCards.add(gameDecks.remove(0));
            }
           
            return dealtCards;
        }

        /**
         * Task: Resets gameDecks by getting all cards from the originalDecks.
         */
        public void reset() {
            // implement this method!
            originalDecks.clear();
            gameDecks.addAll(originalDecks);
        }

        /**
         * Task: Return number of decks.
         */
        public int getNumberDecks() {
            return numberDecks;
        }

        /**
         * Task: Return withJokers.
         */
        public boolean getWithJokers() {
            return withJokers;
        }

        /**
         * Task: Return number of remaining cards in gameDecks.
         */
        public int remainSize() {
            return gameDecks.size();
        }

        /**
         * Task: Returns a string representing cards in the gameDecks
         */
        public String toString() {
            return "" + gameDecks;
        }

        /* Quick test */
        /*                               */
        /* Do not modify these tests */
        /* Generate 2 decks of 54 cards */
        /* Loop 2 times: */
        /* Deal 27 cards for 5 times */
        /* Expect exception at 5th time */
        /* reset() */

        public static void main(String args[]) {

            System.out.println("*******    Create 2 decks of cards      ********\n");
            Decks decks = new Decks(2, true);
            System.out.println("getNumberDecks:" + decks.getNumberDecks());
            System.out.println("getWithJokers:" + decks.getWithJokers());

            for (int j = 0; j < 2; j++) {
                System.out.println("\n************************************************\n");
                System.out.println("Loop # " + j + "\n");
                System.out.println("Before shuffle:" + decks.remainSize() + " cards");
                System.out.println("\n\t" + decks);
                System.out.println("\n==============================================\n");

                int numHands = 5;
                int cardsPerHand = 27;

                for (int i = 0; i < numHands; i++) {
                    decks.shuffle();
                    System.out.println("After shuffle:" + decks.remainSize() + " cards");
                    System.out.println("\n\t" + decks);
                    try {
                        System.out.println("\n\nHand " + i + ":" + cardsPerHand + " cards");
                        System.out.println("\n\t" + decks.deal(cardsPerHand));
                        System.out.println("\n\nRemain:" + decks.remainSize() + " cards");
                        System.out.println("\n\t" + decks);
                        System.out.println("\n==============================================\n");
                    } catch (PlayingCardException e) {
                        System.out.println("*** In catch block:PlayingCardException:Error Msg: " + e.getMessage());
                    }
                }

                decks.reset();
            }
        }

    }
    /*************************************************************************************
     *
     *  This program is used to test PJ4.VideoPoker class
     *  More info are given in Readme file
     *
     *  PJ4 class allows user to run program as follows:
     *
     *        java PJ4        // default credit is $100
     *  or     java PJ4 NNN        // set initial credit to NNN
     *
     *  Do not modify this file!
     *
     **************************************************************************************/

    import PJ4.VideoPoker;

    class TestVideoPoker {

        public static void main(String args[])
        {
        VideoPoker pokergame;
        if (args.length > 0)
            pokergame = new VideoPoker(Integer.parseInt(args[0]));
        else
            pokergame = new VideoPoker();
        pokergame.play();
        }
    }
    package PJ4;

    import java.util.*;

    /*
     * Ref: http://en.wikipedia.org/wiki/Video_poker
     *      http://www.freeslots.com/poker.htm
     *
     *
     * Short Description and Poker rules:
     *
     * Video poker is also known as draw poker.
     * The dealer uses a 52-card deck, which is played fresh after each playerHand.
     * The player is dealt one five-card poker playerHand.
     * After the first draw, which is automatic, you may hold any of the cards and draw
     * again to replace the cards that you haven't chosen to hold.
     * Your cards are compared to a table of winning combinations.
     * The object is to get the best possible combination so that you earn the highest
     * payout on the bet you placed.
     *
     * Winning Combinations
     * 
     * 1. One Pair: one pair of the same card
     * 2. Two Pair: two sets of pairs of the same card denomination.
     * 3. Three of a Kind: three cards of the same denomination.
     * 4. Straight: five consecutive denomination cards of different suit.
     * 5. Flush: five non-consecutive denomination cards of the same suit.
     * 6. Full House: a set of three cards of the same denomination plus
     *     a set of two cards of the same denomination.
     * 7. Four of a kind: four cards of the same denomination.
     * 8. Straight Flush: five consecutive denomination cards of the same suit.
     * 9. Royal Flush: five consecutive denomination cards of the same suit,
     *     starting from 10 and ending with an ace
     *
     */

    /* This is the video poker game class.
     * It uses Decks and Card objects to implement video poker game.
     * Please do not modify any data fields or defined methods
     * You may add new data fields and methods
     * Note: You must implement defined methods
     */

    public class VideoPoker {

        // default constant values
        private static final int startingBalance = 100;
        private static final int numberOfCards = 5;
        private HashMap<Integer, Card> keepCards;
        // default constant payout value and playerHand types
        private static final int[] multipliers = { 1, 2, 3, 5, 6, 10, 25, 50, 1000 };
        private static final String[] goodHandTypes = { "One Pair", "Two Pairs", "Three of a Kind", "Straight", "Flush    ",
                "Full House", "Four of a Kind", "Straight Flush", "Royal Flush" };

        // must use only one deck
        private final Decks oneDeck;

        // holding current poker 5-card hand, balance, bet
        private List<Card> playerHand;
        private int playerBalance;
        private int playerBet;
        private boolean isShowPayoutTable = true;

        /** default constructor, set balance = startingBalance */
        public VideoPoker() {
            this(startingBalance);
            keepCards = new HashMap<>();
        }

        /** constructor, set given balance */
        public VideoPoker(int balance) {
            this.playerBalance = balance;
            oneDeck = new Decks(1, false);
            keepCards = new HashMap<>();
        }

        /**
         * This display the payout table based on multipliers and goodHandTypes
         * arrays
         */
        private void isShowPayoutTable() {
            System.out.println("\n\n");
            System.out.println("Payout Table             Multiplier   ");
            System.out.println("=======================================");
            int size = multipliers.length;
            for (int i = size - 1; i >= 0; i--) {
                System.out.println(goodHandTypes[i] + "\t|\t" + multipliers[i]);
            }
            System.out.println("\n\n");
        }

        /**
         * Check current playerHand using multipliers and goodHandTypes arrays Must
         * print yourHandType (default is "Sorry, you lost") at the end of function.
         * This can be checked by testCheckHands() and main() method.
         */
        private void checkHands() {
            // implement this method!
            int clubsCount = 0;
            int diamondsCount = 0;
            int heartsCount = 0;
            int spadesCount = 0;

            boolean handFound = false;

            for (int i = 0; i < 5; i++) {
                if (playerHand.get(i).getSuit() == 0) {
                    clubsCount++;
                } else if (playerHand.get(i).getSuit() == 1) {
                    diamondsCount++;
                } else if (playerHand.get(i).getSuit() == 2) {
                    heartsCount++;
                } else if (playerHand.get(i).getSuit() == 3) {
                    spadesCount++;
                }
            }

            int[] rankCounter = new int[14];

            for (int c = 0; c < 5; c++) {
                for (int r = 1; r < 14; r++) {
                    if (playerHand.get(c).getRank() == r) {
                        rankCounter[r]++;
                    }
                }
            }

            int[] sameRank = new int[4];
            for (int s = 1; s < rankCounter.length; s++) {
                if (rankCounter[s] > 0) {
                    sameRank[rankCounter[s] - 1]++;
                }
            }

            if (clubsCount == 5 || diamondsCount == 5 || heartsCount == 5 || spadesCount == 5) {
                if (sameRank[0] == 5) {

                    if (rankCounter[13] == 1 && rankCounter[12] == 1 && rankCounter[11] == 1 && rankCounter[10] == 1
                            && rankCounter[1] == 1) {
                        playerBalance += playerBet * multipliers[8];
                        System.out.println("Royal Flush!");
                        handFound = true;
                    } else if (sameRank[0] == 5) {

                        for (int i = 13; i > 4; i--) {
                            if (rankCounter[i] == 1 && rankCounter[i - 1] == 1 && rankCounter[i - 2] == 1
                                    && rankCounter[i - 3] == 1 && rankCounter[i - 4] == 1) {
                                playerBalance += playerBet * multipliers[7];
                                System.out.println("Straight Flush!");
                                handFound = true;
                            }
                        }
                    } else {
                        playerBalance += playerBet * multipliers[4];
                        System.out.println("Flush!");
                        handFound = true;
                    }

                } else {
                    playerBalance += playerBet * multipliers[4];
                    System.out.println("Flush!");
                    handFound = true;
                }
            } else if (sameRank[1] == 1) {
                if (sameRank[0] == 3) {
                    if (rankCounter[13] == 2 || rankCounter[12] == 2 || rankCounter[11] == 2 || rankCounter[1] == 2) {
                        // royal pair!
                        playerBalance += playerBet * multipliers[0];
                        System.out.println("Royal Pair!");
                        handFound = true;
                    } else {
                        System.out.println("Sorry, you lost!");
                    }
                } else if (sameRank[2] == 1) {
                    playerBalance += playerBet * multipliers[4];
                    System.out.println("Full House!");
                    handFound = true;
                }
            } else if (sameRank[0] == 1) {
                if (sameRank[1] == 2) {
                    playerBalance += playerBet * multipliers[1];
                    System.out.println("Two Pairs!");
                    handFound = true;
                } else if (sameRank[3] == 1) {
                    playerBalance += playerBet * multipliers[6];
                    System.out.println("Four of a Kind!");
                    handFound = true;
                }
            } else if (sameRank[2] == 1) {
                playerBalance += playerBet * multipliers[2];
                System.out.println("Three of a Kind!");
                handFound = true;
            } else if (sameRank[0] == 5) {
                for (int i = 13; i > 5; i--) {
                    if (rankCounter[i] == 1 && rankCounter[i - 1] == 1 && rankCounter[i - 2] == 1 && rankCounter[i - 3] == 1
                            && rankCounter[i - 4] == 1) {
                        playerBalance += playerBet * multipliers[3];
                        System.out.println("Straight!");
                        handFound = true;
                    }
                }
                if (handFound == false) {
                    System.out.println("Sorry, you lost!");
                }
            } else if (handFound == false) {
                System.out.println("Sorry, you lost!");
            }

        }

        /*************************************************
         * add new private methods here ....
         *
         *************************************************/
        private void getPlayerPos() {
            Scanner scanner = new Scanner(System.in);
            System.out.print("Enter positions of cards to keep (e.g. 1 4 5 ): ");
            scanner = new Scanner(System.in);
            String input = scanner.nextLine();
            if (input.isEmpty()) {
                return;
            }
            String[] pos = input.trim().split("\\s+");
            try {
                for (int i = 0; i < pos.length; i++) {
                    int position = Integer.parseInt(pos[i]) - 1;
                    Card card = playerHand.get(position);
                    keepCards.put(position, card);
                }
            } catch (Exception e) {
                System.out.println("\nPlease input integers 1-5 only. Try again");
                getPlayerPos();
            }
        }

        private void dealHand() {
            try {
                playerHand = oneDeck.deal(numberOfCards);
            } catch (PlayingCardException e) {
                System.out.println("PlayingCardException: " + e.getMessage());
            }
        }

        private void setHands() {
            dealHand();
            for (Map.Entry<Integer, Card> card : keepCards.entrySet()) {
                playerHand.set(card.getKey(), card.getValue());
            }
            System.out.println(playerHand.toString());
        }

        private void isContinue() {
            Scanner scanner = new Scanner(System.in);
            System.out.println("\nDo you want to play a new game? (y or n)");
            scanner = new Scanner(System.in);
            String input = scanner.nextLine();
            if (input.equals("y")) {
                showTableDisplay();
                play();
            } else if (input.equals("n")) {
                System.out.println("\nBye!");
                System.exit(0);
            } else {
                System.out.println("Please enter (y or n)");
                isContinue();
            }
        }

        private void showTableDisplay() {
            Scanner scanner = new Scanner(System.in);
            System.out.println("\nWant to see payout table (y or n)");
            String input = scanner.nextLine();
            if (input.equals("n")) {
                isShowPayoutTable = false;
            }
        }

        private void getBet() {
            Scanner scanner = new Scanner(System.in);
            System.out.print("Enter bet: ");
            try {
                playerBet = scanner.nextInt();
                if (playerBet > playerBalance) {
                    System.out.println("\nBet is larger than balance, try again");
                    getBet();
                }
            } catch (InputMismatchException e) {
                System.out.println("\nPlease input integers only. Try again");
                getBet();
            }
        }

        public void play() {
            /**
             * The main algorithm for single player poker game
             *
             * Steps: isShowPayoutTable()
             *
             * ++ show balance, get bet verify bet value, update balance reset deck,
             * shuffle deck, deal cards and display cards ask for positions of cards
             * to replace get positions in one input line update cards check hands,
             * display proper messages update balance if there is a payout if
             * balance = O: end of program else ask if the player wants to play a
             * new game if the answer is "no" : end of program else :
             * isShowPayoutTable() if user wants to see it goto ++
             */
            if (isShowPayoutTable) {
                isShowPayoutTable();
            }
            System.out.println("\n\n-----------------------------------");
            System.out.println("\nBalance: $" + playerBalance);
            getBet();
            playerBalance -= playerBet;
            oneDeck.reset();
            oneDeck.shuffle();
            dealHand();
            System.out.println(playerHand.toString());
            getPlayerPos();
            setHands();
            checkHands();
            System.out.println("\nBalance: $" + playerBalance);
            if (playerBalance == 0) {
                System.out.println("\nBye!");
                System.exit(0);
            } else {
                isContinue();
            }

        }

       

        /*************************************************
         * Do not modify methods below
         * /*************************************************
         *
         * /** testCheckHands() is used to test checkHands() method checkHands()
         * should print your current hand type
         */

        public void testCheckHands() {
            try {
                playerHand = new ArrayList<Card>();

                // set Royal Flush
                playerHand.add(new Card(3, 1));
                playerHand.add(new Card(3, 10));
                playerHand.add(new Card(3, 12));
                playerHand.add(new Card(3, 11));
                playerHand.add(new Card(3, 13));
                System.out.println(playerHand);
                checkHands();
                System.out.println("-----------------------------------");

                // set Straight Flush
                playerHand.set(0, new Card(3, 9));
                System.out.println(playerHand);
                checkHands();
                System.out.println("-----------------------------------");

                // set Straight
                playerHand.set(4, new Card(1, 8));
                System.out.println(playerHand);
                checkHands();
                System.out.println("-----------------------------------");

                // set Flush
                playerHand.set(4, new Card(3, 5));
                System.out.println(playerHand);
                checkHands();
                System.out.println("-----------------------------------");

                // "Royal Pair" , "Two Pairs" , "Three of a Kind", "Straight",
                // "Flush ",
                // "Full House", "Four of a Kind", "Straight Flush", "Royal Flush"
                // };

                // set Four of a Kind
                playerHand.clear();
                playerHand.add(new Card(4, 8));
                playerHand.add(new Card(1, 8));
                playerHand.add(new Card(4, 12));
                playerHand.add(new Card(2, 8));
                playerHand.add(new Card(3, 8));
                System.out.println(playerHand);
                checkHands();
                System.out.println("-----------------------------------");

                // set Three of a Kind
                playerHand.set(4, new Card(4, 11));
                System.out.println(playerHand);
                checkHands();
                System.out.println("-----------------------------------");

                // set Full House
                playerHand.set(2, new Card(2, 11));
                System.out.println(playerHand);
                checkHands();
                System.out.println("-----------------------------------");

                // set Two Pairs
                playerHand.set(1, new Card(2, 9));
                System.out.println(playerHand);
                checkHands();
                System.out.println("-----------------------------------");

                // set One Pair
                playerHand.set(0, new Card(2, 3));
                System.out.println(playerHand);
                checkHands();
                System.out.println("-----------------------------------");

                // set One Pair
                playerHand.set(2, new Card(4, 3));
                System.out.println(playerHand);
                checkHands();
                System.out.println("-----------------------------------");

                // set no Pair
                playerHand.set(2, new Card(4, 6));
                System.out.println(playerHand);
                checkHands();
                System.out.println("-----------------------------------");
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }

        /* Quick testCheckHands() */
        public static void main(String args[]) {
            VideoPoker pokergame = new VideoPoker();
            pokergame.testCheckHands();
        }
    }

Answers

(5)
Status NEW Posted 04 Dec 2017 01:12 PM My Price 10.00

-----------  ----------- H-----------ell-----------o S-----------ir/-----------Mad-----------am ----------- Th-----------ank----------- yo-----------u f-----------or -----------you-----------r i-----------nte-----------res-----------t a-----------nd -----------buy-----------ing----------- my----------- po-----------ste-----------d s-----------olu-----------tio-----------n. -----------Ple-----------ase----------- pi-----------ng -----------me -----------on -----------cha-----------t I----------- am----------- on-----------lin-----------e o-----------r i-----------nbo-----------x m-----------e a----------- me-----------ssa-----------ge -----------I w-----------ill----------- be----------- qu-----------ick-----------ly

Not Rated(0)