Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 10 of 10

Thread: Can I get some help fixing this issue?

  1. #1
    Junior Member
    Join Date
    Apr 2013
    Posts
    23
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Can I get some help fixing this issue?

    Basically I have to write a program that plays the card game, 21.

    This is the assignment. I've done most of it but my code has a few issues.
    "
    PART 1:

    You are going to create a simple card game of 21. In this game, the single player has to try to come as close to a score of 21 without going over and beat the computer's score.

    1. Set up a class called PlayingCard. Add a method that returns a string representing its rank and suit. For example, the card with rank 1 and suit 'S' is "Ace of Spades".

    2. Set up a class called DeckOfPlayingCards which contains the following information:

    INSTANCE VARIABLES
    an array of 52 PlayingCard objects
    index of the "top" card in the deck

    METHODS
    constructor - initializes each PlayingCard object to a unique card in a standard deck
    shuffle - randomly permute the order of the cards in the array (see below for a hint) and sets the top card to the first card in the array
    deal - returns the top card in the deck and sets the top card index to the next card

    3. Set up a class TwentyOne with a main method that creates the deck of cards and then allows the user to play the game of 21.
    SHUFFLING

    In order to shuffle the cards, use similar to the following algorithm:

    for i = 0 to 50
    pick a random integer j between i and 51
    swap card i with card j
    end for

    GENERAL GAME RULES

    Each card has a point value based on its rank (the suit is ignored in this game). The cards with ranks 2 through 10 have point values of 2 through 10 respectively. The "face" cards (Jack, Queen, King) have a point value of 10 each. The Ace is considered as 11 points, unless that puts the player over a total of 21 points, in which case it reverts to 1 point instead. For example, the following cards are dealt to the player and the total scores are shown to their right:
    CARD CARD SCORE TOTAL SCORE
    5 of Diamonds 5 5
    Ace of Hearts 11 16
    7 of Clubs 7 13
    3 of Clubs 3 16
    Ace of Spades 1 17
    4 of Hearts 4 21

    In each game, the deck of cards is shuffled, and the user starts with the first two cards of the deck. The user may pick the next card of the deck by inputting "HIT" or the user may stop at this point by inputting "STAY". The user can pick as many cards as he or she wants in order to try to come up with a score as close to 21 without going over. If the user goes over 21 points, the user automatically loses and the computer wins. Otherwise, if the user stops with a total score less than or equal to 21, then the computer plays. The computer starts with the next two cards of the deck. The computer automatically "hits" until its score is at least 17. If the computer goes over 21 (but the user did not), then the user wins automatically. Otherwise, the winner is the player with the higher score. A tie (same total score) is won by the computer.
    INPUT PROCESSING

    Input will come from the keyboard in this game. The user should input "HIT" or "STAY" (lowercase ok) as the game proceeds. Any other input should flag an error "Unrecognized input", etc. and you should ask for the input again. At the end of the game, you should ask the user if he/she wants to play again. The input here will be "Y" or "N" (lowercase ok). All other input will lead to an error and you should ask the user to input again. See OUTPUT PROCESSING for an example of correct input.
    OUTPUT PROCESSING

    Here is a sample of the output of the program (user input in purple italics):

    LET'S PLAY 21!
    SHUFFLING CARDS...

    YOUR TURN
    5 of Diamonds 5
    Ace of Hearts 16
    HIT or STAY? HIT
    7 of Clubs 13
    HIT or STAY? hit
    3 of Clubs 16
    HIT or STAY? HIT
    Ace of Spades 17
    HIT or STAY? hit
    4 of Hearts 21
    HIT or STAY? STAY

    COMPUTER'S TURN
    King of Clubs 10
    9 of Diamonds 19

    YOUR SCORE: 21
    COMPUTER'S SCORE: 19
    YOU WIN!
    PLAY AGAIN? (Y/N) Y


    LET'S PLAY 21!
    SHUFFLING CARDS...

    YOUR TURN
    8 of Hearts 8
    Queen of Spades 18
    HIT or STAY? stay

    COMPUTER'S TURN
    Jack of Hearts 10
    3 of Clubs 13
    7 of Spades 20

    YOUR SCORE: 18
    COMPUTER'S SCORE: 20
    YOU LOSE!
    PLAY AGAIN? (Y/N) Y


    LET'S PLAY 21!
    SHUFFLING CARDS...

    YOUR TURN
    Queen of Hearts 10
    5 of Diamonds 15
    HIT or STAY? HIT
    7 of Hearts 22

    YOU LOSE!
    PLAY AGAIN? (Y/N) Y


    LET'S PLAY 21!
    SHUFFLING CARDS...

    YOUR TURN
    4 of Spades 4
    10 of Clubs 14
    HIT or STAY? HIT
    6 of Hearts 20
    HIT or STAY? STAY

    COMPUTER'S TURN
    5 of Hearts 5
    Jack of Spades 15
    Ace of Diamonds 16
    4 of Clubs 20

    YOUR SCORE: 20
    COMPUTER'S SCORE: 20
    YOU LOSE!
    PLAY AGAIN? (Y/N) Y


    LET'S PLAY 21!
    SHUFFLING CARDS...

    YOUR TURN
    8 of Hearts 8
    9 of Diamonds 17
    HIT or STAY? STAY

    COMPUTER'S TURN
    King of Clubs 10
    6 of Spades 16
    Jack of Diamonds 26

    YOU WIN!
    PLAY AGAIN? (Y/N) N"

    --- Update ---

    Here is my code. It's divided into the classes that were stipulated in the assignment.

    public class PlayingCard {
     
    	// instance variables
     
    	private static int rank; // rank of card
     
     
     
    	private static char suit;// card's suit
     
     
     
     
    	// default constructor
     
     
    	// setter method for Rank
    	public static void setRank(int i) {
     
    		rank = i;
    	}
     
    	// getter method for Rank
    	public static int  getRank() {
     
    		return rank;
    	}
    	// setter method for Suit
    	public static void setSuit(char i ) {
     
    		suit = i;
    	}
     
    	// getter method for suit
    	public static char  getSuit() {
     
    		return suit;
    	}
     
    	// cardInfo method. It accepts parameters, 2 string arrays, rank, and suit to return string that indicates the card's name and suit
    	public static String cardInfo(String [] rankstr, String[] suitstr, int rank,  char suit) {
     
     
    		//  The logic behind this declaration is the following. This code will use the char input and discern int's nature in if statements and then assign corresponding index values so that I can use that index to access the right string in the array of characters
    		int suitindex =0;
     
    		// The suits are ordered from least to greatest value. S,H,D,C. That is the order
    		if(suit=='S')
     
    		suitindex =1;
     
    		if(suit=='H')
     
    		suitindex = 2;
     
    		if(suit=='D')
     
    		suitindex =3;
     
    		if(suit=='C')
     
    		suitindex=4;
     
    	// String variable r is used to store the string at index rank.
     
    	String r =rankstr[rank];
     
    	// String variable s is used to store the string at the suitindex obtained previously.
     
    	String s = suitstr[suitindex];
     
     
    	// String info is essentially a concatenation of r and s along with "of".
    	String info = r+"  of  " + s;
     
    	return info;
     
     
     
     
    	}
     
    	public static void main(String [] args) {
     
     
    		Scanner input = new Scanner(System.in);
     
    		// String array of names that correspond with ranks
     
    		String r[] = {null,"Ace", "King", " Queen " , "Jack", "Ten", "Nine", "Eight ", " Seven", "Six"," Five", "Four", "Three", " Dueces"};
     
    		// String array of suits corresponding to ranks
     
    		String s[] = { null, "Spades", " Hearts", "Diamonds ", "Clubs"};
     
    		// Prompt user for input
     
    		System.out.println("Enter card rank and suit");
     
    		int rank = input.nextInt();
     
    		String str = input.next();
    		// Method "charAt" is used to find the character at index zero because scanners don't work for characters.
    		char suit = str.charAt(0);
     
    		PlayingCard nm = new PlayingCard();
     
    		String m =nm.cardInfo(r, s, rank, suit);
    		// PlayingCard object
    		System.out.println(m);
     
    		// Value returned by the invocation of the cardInfo method is stored in s1;
     
     
    		// s1 is now being printed
     
    }
    }

    import java.util.Arrays;
     
     
     
    public class DeckOfPlayingCards {
     
        private static PlayingCard cards[] = new PlayingCard[52];
     
        private static int  indexOftop =51;
     
    	String rankstr[] = {"Ace", "King", " Queen " , "Jack", "Ten", "Nine", "Eight ", " Seven", "Six"," Five", "Four", "Three", " Dueces"};
     
     
     
    	String suitstr[] = {  "Spades", " Hearts", "Diamonds ", "Clubs"};
     
     
     
     
        public void setCards() {
     
            this.cards = cards;
        }
     
        public PlayingCard[] getCards() {
     
     
     
    		return cards;
        }
     
        public void setIndexOftop() {
     
            this.indexOftop= indexOftop;
        }
     
        public int getIndexOftop() {
     
        	return indexOftop;
        }
     
        public DeckOfPlayingCards() {
     
        for(int i =0; i<cards.length; i++) {
     
        	int rank =cards[i].getRank();
     
        	char suit = cards[i].getSuit();
     
        	cards[i]=new PlayingCard();
     
            cards[i].cardInfo(rankstr, suitstr, rank, suit);
     
        }}
     
        public void shuffle(){
     
        	int j;
     
            for(int i = 0 ; i<51; i++) {
     
            j = (int)Math.random()*51;
     
            PlayingCard temp = cards[i];
     
            cards[i]=cards[j];
     
            cards[j]=temp;
     
            temp = cards[0]; 
     
     
            cards[0]=cards[indexOftop];
            }
     
     
     
     
    }
     
        public PlayingCard deal() {
     
     
            for(int i=0; i<51; i++){
     
     
            indexOftop=52;
     
            indexOftop -=i;
            }
     
            return cards[indexOftop];
     
     
     
     
     
        }
     
    }

    import java.util.Scanner;
     
     
     
    public class TwentyOne {
     
     
    public static void main(String [] args) {
     
    	Scanner input = new Scanner(System.in);
     
    	DeckOfPlayingCards deck = new DeckOfPlayingCards();
     
     
    	// String array of  ranks
     
    	String rankstr[] = {  "Ace", "2", " 3 " , "4", "5", "6", "7 ", " 8", "9"," 10", "Jack", "Queen", " King"};
     
    	// String array of suits corresponding to ranks
     
    	String suitstr[] = {  "Spades", " Hearts", "Diamonds ", "Clubs"}; 
     
    	gamePlay(rankstr,suitstr,deck);
     
    	System.out.println("DO YOU WANT TO PLAY AGAIN? Y OR N");
     
    	String answer = input.next();
     
    	while(answer.equals("Y")) {
     
    	gamePlay(suitstr, suitstr, deck);
     
    	if(answer.equals("N")) {
     
     
     
    	System.out.println("THANK YOU FOR PLAYING");
     
    	break;
     
    	}}
     
    }
     
    		public static void gamePlay(String rankstr[],String suitstr[],DeckOfPlayingCards deck) {
     
    			Scanner input = new Scanner(System.in);
     
    		// Initialization of rank and index number of suit array.
    		int rank = (int)Math.random();
     
     
    		int suitIndex = (int)Math.random();
    	// Represents the score of the user 
    		int total;
    		// A secondary variable for user's score. Its use will become more apparent as you progress through the program
    		int tot =0;
     
    		// Represents computer's score
    		int totcomputer =0;
     
    		// suitIndex is used to get a string from the array and then charAt() is used to find the first character
    		String str= suitstr[suitIndex];
     
    		char suit = str.charAt(0);
     
    		// Game 
    		System.out.println("LET'S PLAY 21!");
     
    		System.out.println();
     
    		System.out.println();
     
    		System.out.println("SHUFFLING CARDS...");
     
    		System.out.println();
     
    		 deck.shuffle();
     
    		 System.out.println();
     
    		System.out.println("YOUR TURN");
    		 // I'm adding 1 to rank b/c the first element in the array of ranks is the ranked number 1 and so on and so forth for the other elements
    		 total = rank+1;
     
    		 // Print first card
    		 System.out.println(deck.deal().cardInfo(rankstr, suitstr, rank, suit) +" " +"\t\t\t" + total);
     
    		 		deck.shuffle();
     
     
    			 rank = (int)((Math.random()*rankstr.length-1));
     
    			suitIndex = (int)((Math.random()*suitstr.length-1));
     
    			str= suitstr[suitIndex];
     
    			suit = str.charAt(0);
     
     
    			 total = rank+1;
     
    		 // Print second card
    		 System.out.println(deck.deal().cardInfo(rankstr, suitstr, rank, suit) +" " +"\t\t\t" + total);
     
    		 deck.shuffle();
     
     
    		 System.out.println("HIT OR STAY");
     
    		 String response = input.next();
     
    		 // When user decides to hit, more cards will be played
    		 while(response.equals("HIT")||response.equals("hit")) {
     
    			 rank = (int)((Math.random()*rankstr.length-1));
     
    			 suitIndex = (int)((Math.random()*suitstr.length-1));
     
    			 str= suitstr[suitIndex];
     
    			 suit = str.charAt(0);
     
    			 tot+=rank+1;
     
    			 if(rank==0)
     
    				 rank=10;
     
    			 if(tot>21&&rank==11)
     
    				rank =0;
     
     
     
    		System.out.println(deck.deal().cardInfo(rankstr, suitstr, rank, suit) + " " +"\t\t\t" + tot);
     
    		deck.shuffle();
     
    			if(tot==21){
     
    			System.out.println("YOU WIN");
     
    			break;}
     
    			if(tot>21){
     
    			System.out.println("YOU LOSE. THE COMPUTER WINS"); 
     
    			break;
     
     
     
    			}
     
    			System.out.println("HIT OR STAY");
     
    			response = input.next();
    		// When user is done
    		  if(response.equals("STAY")||response.equals("stay")) {
     
    				  System.out.println("COMPUTER'S TURN");
     
     
    				 do { 
     
    					 rank =  (int)((Math.random()*rankstr.length-1));
     
     
    					 suitIndex = (int)((Math.random()*suitstr.length-1));
     
     
     
    					 str= suitstr[suitIndex];
     
     
     
     
    					 suit = str.charAt(0);
     
    					 totcomputer+=rank+1;
     
    					 if(rank==1)
     
    						 rank=11;
     
    					 if(totcomputer>21&&rank==11)
     
    						rank =1;
     
    					 deck.shuffle();
     
    				  System.out.println(deck.deal().cardInfo(rankstr, suitstr, rank, suit) +" " +"\t\t\t" + totcomputer);
     
    				  if(totcomputer==21) {
     
    					  System.out.println("THE COMPUTER WINS");
    				  		break;}
     
    					 if(totcomputer>21&&tot<=21){
     
    						 System.out.println();
     
    					 	System.out.println();
     
    						 System.out.println("YOU WIN");
     
    						 break;
    					 }
    				 }
    				  while(totcomputer<=17);
     
    				 System.out.println();
     
    				 System.out.println();
     
    				 System.out.println();
     
    				 System.out.println("YOUR SCORE" + " " + tot + "        "+  "COMPUTER'S SCORE" + "        " + totcomputer);
     
     
     
     
    				 if(tot<21&&totcomputer<21&&tot>totcomputer){
     
    					 System.out.println();
     
    					System.out.println("YOU WIN");}
     
    				 if(tot<21&&totcomputer<21&&tot<totcomputer){
     
    					 System.out.println();
     
    					 System.out.println("YOU LOSE. THE COMPUTER WINS");}
     
    				 if(tot==totcomputer&&tot<=21&&tot>=21) {
     
    					 System.out.println();
     
    					System.out.println("THE COMPUTER IS THE WINNER");
    			  }
     
    				 if(tot==totcomputer&&tot<21&&totcomputer<21) {
     
    					 System.out.println();
     
    					System.out.println("THE COMPUTER IS THE WINNER"); }
    				 }}
     
    		 }}


    --- Update ---

    I keep getting indexoutofbounds exceptions and sometimes for my cardInfo method, 2 suits are printed instead of a rank and a suit. Can I please get some help? I'd really appreciate it. Thanks in advance!

    --- Update ---

    I keep getting indexoutofbounds exceptions and sometimes for my cardInfo method, 2 suits are printed instead of a rank and a suit. Can I please get some help? I'd really appreciate it. Thanks in advance!


  2. #2
    Junior Member
    Join Date
    Jul 2013
    Posts
    16
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Re: Can I get some help fixing this issue?

    Index out of bounds usually menas that you are referring to an array element that doesn't exist. This may mean that whatever you are using to obtain the array elements loops too long. Remember, arrays start at 0. so if you have 9 elements in your array, the computer sees it as 8 ( because of 0 being the first elemenet) I hope I have helped a bit

    hannes

  3. #3
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Can I get some help fixing this issue?

    Post your errors, copied and pasted into code tags if they're long, and show sample runs where the cardInfo() method output is incorrect.

  4. #4
    Junior Member
    Join Date
    Apr 2013
    Posts
    23
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can I get some help fixing this issue?

    Quote Originally Posted by GregBrannon View Post
    Post your errors, copied and pasted into code tags if they're long, and show sample runs where the cardInfo() method output is incorrect.
    Here is one of the outputs:

    It worked fine until after the game was over and I prompted the user to say whether or not he wants to play again and when the game restarted, the output displayed " Hearts of Hearts 2", it's displaying two suits instead of a rank and a suit. That shouldn't be happening and I can't figure out why it happened.

    LET'S PLAY 21!


    SHUFFLING CARDS...


    YOUR TURN
    Ace of Hearts 1
    Ace of Clubs 1
    HIT OR STAY
    hit
    2 of Hearts 2
    HIT OR STAY
    hit
    Queen of Hearts 14
    HIT OR STAY
    stay
    COMPUTER'S TURN
    5 of Spades 5
    Ace of Spades 6
    Ace of Clubs 7
    4 of Spades 11
    Queen of Hearts 13
    10 of Spades 23


    YOU WIN



    YOUR SCORE 14 COMPUTER'S SCORE 23
    DO YOU WANT TO PLAY AGAIN? Y OR N
    Y
    LET'S PLAY 21!


    SHUFFLING CARDS...


    YOUR TURN
    Spades of Hearts 1
    Hearts of Hearts 2
    HIT OR STAY

    --- Update ---

    Here's another sample output: I got an array index out of bounds exception and the output displayed two suits instead of a rank and a suit.

    LET'S PLAY 21!


    SHUFFLING CARDS...


    YOUR TURN
    Ace of Hearts 1
    Ace of Hearts 1
    HIT OR STAY
    hit
    7 of Clubs 7
    HIT OR STAY
    hit
    7 of Clubs 14
    HIT OR STAY
    hit
    5 of Spades 19
    HIT OR STAY
    hit
    10 of Hearts 29
    YOU LOSE. THE COMPUTER WINS
    DO YOU WANT TO PLAY AGAIN? Y OR N
    Y
    LET'S PLAY 21!


    SHUFFLING CARDS...


    YOUR TURN
    Spades of Hearts 1
    Spades of Spades 1
    HIT OR STAY
    hit
    Hearts of Hearts 2
    HIT OR STAY
    hit
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
    at PlayingCard.cardInfo(PlayingCard.java:70)
    at TwentyOne.gamePlay(TwentyOne.java:136)
    at TwentyOne.main(TwentyOne.java:31)

  5. #5
    Junior Member
    Join Date
    Apr 2013
    Posts
    23
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can I get some help fixing this issue?

    Quote Originally Posted by cbplayer View Post
    Here is one of the outputs:

    It worked fine until after the game was over and I prompted the user to say whether or not he wants to play again and when the game restarted, the output displayed " Hearts of Hearts 2", it's displaying two suits instead of a rank and a suit. That shouldn't be happening and I can't figure out why it happened.

    LET'S PLAY 21!


    SHUFFLING CARDS...


    YOUR TURN
    Ace of Hearts 1
    Ace of Clubs 1
    HIT OR STAY
    hit
    2 of Hearts 2
    HIT OR STAY
    hit
    Queen of Hearts 14
    HIT OR STAY
    stay
    COMPUTER'S TURN
    5 of Spades 5
    Ace of Spades 6
    Ace of Clubs 7
    4 of Spades 11
    Queen of Hearts 13
    10 of Spades 23


    YOU WIN



    YOUR SCORE 14 COMPUTER'S SCORE 23
    DO YOU WANT TO PLAY AGAIN? Y OR N
    Y
    LET'S PLAY 21!


    SHUFFLING CARDS...


    YOUR TURN
    Spades of Hearts 1
    Hearts of Hearts 2
    HIT OR STAY

    --- Update ---

    Here's another sample output: I got an array index out of bounds exception and the output displayed two suits instead of a rank and a suit.

    LET'S PLAY 21!


    SHUFFLING CARDS...


    YOUR TURN
    Ace of Hearts 1
    Ace of Hearts 1
    HIT OR STAY
    hit
    7 of Clubs 7
    HIT OR STAY
    hit
    7 of Clubs 14
    HIT OR STAY
    hit
    5 of Spades 19
    HIT OR STAY
    hit
    10 of Hearts 29
    YOU LOSE. THE COMPUTER WINS
    DO YOU WANT TO PLAY AGAIN? Y OR N
    Y
    LET'S PLAY 21!


    SHUFFLING CARDS...


    YOUR TURN
    Spades of Hearts 1
    Spades of Spades 1
    HIT OR STAY
    hit
    Hearts of Hearts 2
    HIT OR STAY
    hit
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
    at PlayingCard.cardInfo(PlayingCard.java:70)
    at TwentyOne.gamePlay(TwentyOne.java:136)
    at TwentyOne.main(TwentyOne.java:31)
    Can I please get some help?

  6. #6
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Can I get some help fixing this issue?

    You don't need to quote your whole last post, or any part of it for that matter, to "bump" your thread. Be patient.

    This line:

    gamePlay(suitstr, suitstr, deck);

    in the while() clause at the end of the TwentyOne.main() method is probably the source of both of the errors for which you've asked for help.

    Also, the game play is 'off'. Here's a run I experienced:
    LET'S PLAY 21!
     
     
    SHUFFLING CARDS...
     
     
    YOUR TURN
    Ace  of   Hearts 			1
    Queen  of   Hearts 			12
    HIT OR STAY
    hit
    7   of  Spades 			7
    HIT OR STAY
    stay
    COMPUTER'S TURN
    Queen  of   Hearts 			12
    7   of   Hearts 			19
     
    YOUR SCORE 7        COMPUTER'S SCORE        19
     
    YOU LOSE. THE COMPUTER WINS
    DO YOU WANT TO PLAY AGAIN? Y OR N
     
     
    y
    LET'S PLAY 21!
     
     
    SHUFFLING CARDS...
     
     
    YOUR TURN
    Spades  of   Hearts 			1
    Spades  of  Spades 			1
    HIT OR STAY
    I admit that I'm lousy at Blackjack, and maybe the results would have been different if I'd have stayed rather than hit, but the card values, results and/or totals are not correct. In the Blackjack I know, an Ace with any face card would have been Blackjack, and the value of any face card is 10.

    Other items I noticed:

    PlayingCard.cardInfo(), .getRank(), and getSuit are static methods and should either be changed to non-static (I believe the preference) or referred to in a static way.

    DeckOfPlayingCards.setCard() and .setIndexOftop() methods are pointless.

    Let us know how you're doing after addressing those points and if you need additional help.

  7. #7
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Can I get some help fixing this issue?

    You don't need to quote your whole last post, or any part of it for that matter, to "bump" your thread. Be patient.

    This line:

    gamePlay(suitstr, suitstr, deck);

    in the while() clause at the end of the TwentyOne.main() method is probably the source of both of the errors for which you've asked for help.

    Also, the game play is 'off'. Here's a run I experienced:
    LET'S PLAY 21!
     
     
    SHUFFLING CARDS...
     
     
    YOUR TURN
    Ace  of   Hearts 			1
    Queen  of   Hearts 			12
    HIT OR STAY
    hit
    7   of  Spades 			7
    HIT OR STAY
    stay
    COMPUTER'S TURN
    Queen  of   Hearts 			12
    7   of   Hearts 			19
     
    YOUR SCORE 7        COMPUTER'S SCORE        19
     
    YOU LOSE. THE COMPUTER WINS
    DO YOU WANT TO PLAY AGAIN? Y OR N
     
     
    y
    LET'S PLAY 21!
     
     
    SHUFFLING CARDS...
     
     
    YOUR TURN
    Spades  of   Hearts 			1
    Spades  of  Spades 			1
    HIT OR STAY
    I admit that I'm lousy at Blackjack, and maybe the results would have been different if I'd have stayed rather than hit, but the card values, results and/or totals are not correct. In the Blackjack I know, an Ace with any face card would have been Blackjack, and the value of any face card is 10.

    Other items I noticed:

    PlayingCard.cardInfo(), .getRank(), and getSuit are static methods and should either be changed to non-static (I believe the preference) or referred to in a static way.

    DeckOfPlayingCards.setCard() and .setIndexOftop() methods are pointless.

    Let us know how you're doing after addressing those points and if you need additional help.

  8. #8
    Junior Member
    Join Date
    Apr 2013
    Posts
    23
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can I get some help fixing this issue?

    Dont my total and values line up with sample output given my the instructor?

    Also I fixed some of the issues you mentioned but I'm having trouble with another issue. Sometimes when the play wins, instead of asking the user if he wants to play again, it simply runs the game again. Also sometimes when I hit stay, the game just starts all over again.

    SAMPLE OUTPUT:

    SHUFFLING CARDS...


    YOUR TURN
    Queen of Spades 12
    8 of Spades 8
    HIT OR STAY
    hit
    9 of Spades 9
    HIT OR STAY
    hit
    7 of Diamonds 16
    HIT OR STAY
    hit
    4 of Spades 20
    HIT OR STAY
    stay
    COMPUTER'S TURN
    King of Clubs 13
    5 of Spades 18



    YOUR SCORE 20 COMPUTER'S SCORE 18

    YOU WIN
    LET'S PLAY 21!


    SHUFFLING CARDS...


    YOUR TURN
    10 of Spades 10
    Queen of Spades 12
    HIT OR STAY




    here is my code

    import java.util.Scanner;
     
     
     
    public class TwentyOne {
     
     
    public static void main(String [] args) {
     
    	Scanner input = new Scanner(System.in);
     
    	DeckOfPlayingCards deck = new DeckOfPlayingCards();
     
     
    	// String array of  ranks
     
    	String rankstr[] = {  "Ace", "2", " 3 " , "4", "5", "6", "7 ", " 8", "9"," 10", "Jack", "Queen", " King"};
     
    	// String array of suits corresponding to ranks
     
    	String suitstr[] = {  "Spades", " Hearts", "Diamonds ", "Clubs"}; 
     
    	gamePlay(rankstr,suitstr,deck);
     
    	System.out.println("DO YOU WANT TO PLAY AGAIN? Y OR N");
     
    	String answer = input.next();
     
    	while(answer.equals("Y")||answer.equals("y")) {
     
    	gamePlay(rankstr, suitstr, deck);
     
    	if(answer.equals("N")||answer.equals("n")) {
     
    	break;
     
    	}}
     
    }
     
    		public static void gamePlay(String rankstr[],String suitstr[],DeckOfPlayingCards deck) {
     
    			Scanner input = new Scanner(System.in);
     
    		// Initialization of rank and index number of suit array.
    		int rank = (int)(Math.random()*rankstr.length);
     
     
    		int suitIndex = (int)Math.random()*suitstr.length;
    	// Represents the score of the user 
    		int total;
    		// A secondary variable for user's score. Its use will become more apparent as you progress through the program
    		int tot =0;
     
    		// Represents computer's score
    		int totcomputer =0;
     
    		// suitIndex is used to get a string from the array and then charAt() is used to find the first character
    		String str= suitstr[suitIndex];
     
    		char suit = str.charAt(0);
     
    		// Game 
    		System.out.println("LET'S PLAY 21!");
     
    		System.out.println();
     
    		System.out.println();
     
    		System.out.println("SHUFFLING CARDS...");
     
    		System.out.println();
     
    		 deck.shuffle();
     
    		 System.out.println();
     
    		System.out.println("YOUR TURN");
    		 // I'm adding 1 to rank b/c the first element in the array of ranks is the ranked number 1 and so on and so forth for the other elements
    		 total = rank+1;
     
    		 // Print first card
    		 System.out.println(deck.deal().cardInfo(rankstr, suitstr, rank, suit) +" " +"\t\t\t" + total);
     
    		 		deck.shuffle();
     
     
    			 rank = (int)((Math.random()*rankstr.length));
     
    			suitIndex = (int)((Math.random()*suitstr.length));
     
    			str= suitstr[suitIndex];
     
    			suit = str.charAt(0);
     
     
    			 total = rank+1;
     
    		 deck.deal();
    		// Print second card
     
    		 deck.shuffle();
     
    		 System.out.println(PlayingCard.cardInfo(rankstr, suitstr, rank, suit) +" " +"\t\t\t" + total);
     
     
     
     
    		 System.out.println("HIT OR STAY");
     
    		 String response = input.next();
     
    		 // When user decides to hit, more cards will be played
    		 while(response.equals("HIT")||response.equals("hit")) {
     
    			 rank = (int)((Math.random()*rankstr.length-1));
     
    			 suitIndex = (int)((Math.random()*suitstr.length-1));
     
    			 str= suitstr[suitIndex];
     
    			 suit = str.charAt(0);
     
    			 tot+=rank+1;
     
    			 if(rank==0)
     
    				 rank=10;
     
    			 if(tot>21&&rank==11)
     
    				rank =0;
     
     
     
    		System.out.println(deck.deal().cardInfo(rankstr, suitstr, rank, suit) + " " +"\t\t\t" + tot);
     
    		deck.shuffle();
     
    			if(tot==21){
     
    			System.out.println("YOU WIN");
     
    			break;
     
    			}
     
    			if(tot>21){
     
    			System.out.println("YOU LOSE. THE COMPUTER WINS");
    			break;
    			}
     
    			System.out.println("HIT OR STAY");
     
    			response = input.next();
    		// When user is done
    		  if(response.equals("STAY")||response.equals("stay")) {
     
    				  System.out.println("COMPUTER'S TURN");
     
     
    				 do { 
     
    					 rank =  (int)((Math.random()*rankstr.length));
     
     
    					 suitIndex = (int)((Math.random()*suitstr.length));
     
     
     
    					 str= suitstr[suitIndex];
     
     
     
     
    					 suit = str.charAt(0);
     
    					 totcomputer+=rank+1;
     
    					 if(rank==1)
     
    						 rank=11;
     
    					 if(totcomputer>21&&rank==11)
     
    						rank =1;
     
    					 deck.shuffle();
     
    				  deck.deal();
    				System.out.println(PlayingCard.cardInfo(rankstr, suitstr, rank, suit) +" " +"\t\t\t" + totcomputer);
     
    				  if(totcomputer==21) {
     
    					  System.out.println("THE COMPUTER WINS");
    				  		break;}
     
    					 if(totcomputer>21&&tot<=21){
     
    						 System.out.println();
     
    					 	System.out.println();
     
    						 System.out.println("YOU WIN");
     
    						 break;
    					 }
    				 }
    				  while(totcomputer<=17);
     
    				 System.out.println();
     
    				 System.out.println();
     
    				 System.out.println();
     
    				 System.out.println("YOUR SCORE" + " " + tot + "        "+  "COMPUTER'S SCORE" + "        " + totcomputer);
     
     
     
     
    				 if(tot<21&&totcomputer<21&&tot>totcomputer){
     
    					 System.out.println();
     
    					System.out.println("YOU WIN");
    					break;}
     
    				 if(tot<21&&totcomputer<21&&tot<totcomputer){
     
    					 System.out.println();
     
    					 System.out.println("YOU LOSE. THE COMPUTER WINS"); break;}
     
    				 if(tot==totcomputer&&tot<=21&&tot>=21) {
     
    					 System.out.println();
     
    					System.out.println("THE COMPUTER IS THE WINNER");
     
    					break;
    			  }
     
    				 if(tot==totcomputer&&tot<21&&totcomputer<21) {
     
    					 System.out.println();
     
    					System.out.println("THE COMPUTER IS THE WINNER");
     
    				 break;}
    				 }}
     
    		 }}

  9. #9
    Junior Member
    Join Date
    Apr 2013
    Posts
    23
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can I get some help fixing this issue?

    Anybody??

    --- Update ---

    I fixed several of the issues but one issue remains. If I input "stay" before I input 'hit" the computer's cards don't print. Please try to help. I really need to get this done.

    example :
    LET'S PLAY 21!


    SHUFFLING CARDS...


    YOUR TURN
    Jack of Spades 11
    King of Diamonds 24
    HIT OR STAY
    stay



    YOUR SCORE 0 COMPUTER'S SCORE 0
    DO YOU WANT TO PLAY AGAIN? Y OR N


    [code==java]import java.util.Scanner;



    public class TwentyOne {


    public static void main(String [] args) {

    Scanner input = new Scanner(System.in);

    DeckOfPlayingCards deck = new DeckOfPlayingCards();


    // String array of ranks

    String rankstr[] = { "Ace", "2", " 3 " , "4", "5", "6", "7 ", " 8", "9"," 10", "Jack", "Queen", " King"};

    // String array of suits corresponding to ranks

    String suitstr[] = { "Spades", " Hearts", "Diamonds ", "Clubs"};

    deck.shuffle();

    gamePlay(rankstr,suitstr,deck);




    } public static void gamePlay(String rankstr[],String suitstr[],DeckOfPlayingCards deck) {

    Scanner input = new Scanner(System.in);

    // Initialization of rank and index number of suit array.
    int rank = (int)(Math.random()*rankstr.length);


    int suitIndex = (int)Math.random()*suitstr.length;
    // Represents the score of the user
    int total;
    // A secondary variable for user's score. Its use will become more apparent as you progress through the program
    int tot =0;

    // Represents computer's score
    int totcomputer =0;

    // suitIndex is used to get a string from the array and then charAt() is used to find the first character
    String str= suitstr[suitIndex];

    char suit = str.charAt(0);

    // Game
    System.out.println("LET'S PLAY 21!");

    System.out.println();

    System.out.println();

    System.out.println("SHUFFLING CARDS...");

    System.out.println();

    deck.shuffle();

    System.out.println();

    System.out.println("YOUR TURN");
    // I'm adding 1 to rank b/c the first element in the array of ranks is the ranked number 1 and so on and so forth for the other elements
    total = rank+1;

    // Print first card
    System.out.println(deck.deal().cardInfo(rankstr, suitstr, rank, suit) +" " +"\t\t\t" + total);

    deck.shuffle();


    rank = (int)((Math.random()*rankstr.length));

    suitIndex = (int)((Math.random()*suitstr.length));

    str= suitstr[suitIndex];

    suit = str.charAt(0);


    total = total+rank+1;

    // Print second card
    System.out.println(deck.deal().cardInfo(rankstr, suitstr, rank, suit) +" " +"\t\t\t" + total);

    deck.shuffle();


    System.out.println("HIT OR STAY");

    String response = input.next();

    // When user decides to hit, more cards will be played
    while(response.equals("HIT")||response.equals("hit ")) {

    rank = (int)((Math.random()*rankstr.length-1));

    suitIndex = (int)((Math.random()*suitstr.length-1));

    str= suitstr[suitIndex];

    suit = str.charAt(0);

    tot+=rank+1;

    if(rank==0)

    rank=10;

    if(tot>21&&rank==11)

    rank =0;



    System.out.println(deck.deal().cardInfo(rankstr, suitstr, rank, suit) + " " +"\t\t\t" + tot);

    deck.shuffle();

    if(tot==21){

    System.out.println("YOU WIN");

    break;}

    if(tot>21){

    System.out.println("YOU LOSE. THE COMPUTER WINS");

    break;



    }

    System.out.println("HIT OR STAY");

    response = input.next();
    // When user is done




    if((response.equals("STAY")||response.equals("stay ")))

    System.out.println("COMPUTER'S TURN");
    do{


    rank = (int)((Math.random()*rankstr.length));


    suitIndex = (int)((Math.random()*suitstr.length));



    str= suitstr[suitIndex];




    suit = str.charAt(0);

    totcomputer+=rank+1;

    if(rank==1)

    rank=11;

    if(totcomputer>21&&rank==11)

    rank =1;

    deck.shuffle();

    System.out.println(deck.deal().cardInfo(rankstr, suitstr, rank, suit) +" " +"\t\t\t" + totcomputer);

    if(totcomputer==21) {

    System.out.println("THE COMPUTER WINS");
    break;}

    if(totcomputer>21&&tot<=21){

    System.out.println();

    System.out.println();

    System.out.println("YOU WIN");

    break;
    }
    }while(totcomputer<=17);
    if(tot<21&&totcomputer<21&&tot>totcomputer){

    System.out.println();

    System.out.println("YOU WIN");}

    if(tot<21&&totcomputer<21&&tot<totcomputer){

    System.out.println();

    System.out.println("YOU LOSE. THE COMPUTER WINS");}

    if(tot==totcomputer&&tot<=21&&tot>=21) {

    System.out.println();

    System.out.println("THE COMPUTER IS THE WINNER");
    }

    if(tot==totcomputer&&tot<21&&totcomputer<21) {

    System.out.println();

    System.out.println("THE COMPUTER IS THE WINNER"); }
    }



    System.out.println();

    System.out.println();

    System.out.println();

    System.out.println("YOUR SCORE" + " " + tot + " "+ "COMPUTER'S SCORE" + " " + totcomputer);




    System.out.println("DO YOU WANT TO PLAY AGAIN? Y OR N");

    String answer = input.next();





    while(answer.equals("Y")) {

    gamePlay(rankstr, suitstr, deck);

    if(answer.equals("N"))

    System.out.println("THANK YOU FOR PLAYING");
    break;
    }


    }}[/code ]

  10. #10
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Can I get some help fixing this issue?

    The output below is clearly not correct. I recommend you consult the rules of Blackjack:
    YOUR TURN
    Jack of Spades 11
    King of Diamonds 24
    HIT OR STAY
    stay
    Returning the correct value of a card would be a good use of Java's ternary operator:
        // returns the card's value according to the rules of Blackjack
        public int getValue()
        {
            return rankIndex + 1 > 10 ? 10 : rankIndex + 1;
        }
    Though an incorrect total, the Player's score of 24 ends the current game (breaks out of the while statement), and starts a new game. The player busted. The option to HIT or STAY shouldn't even be given, because it and the dealer's score are irrelevant.

    Other comments:

    The Scanner input is never used in the main() method, but it probably should be. The main() method design might be something like:
        public static void main(String [] args)
        {
            boolean playAgain;
            DeckOfPlayingCards deck = new DeckOfPlayingCards();
            Scanner input = new Scanner( System.in );
     
            do
            {
                gamePlay( deck );
     
                playAgain = false;
     
                System.out.println("DO YOU WANT TO PLAY AGAIN? Y OR N");
     
                String answer = input.next();
     
                if( answer.equalsIgnoreCase("Y") )
                {
                    playAgain = true;
                }
     
            }
            while ( playAgain );
     
            System.out.println("THANK YOU FOR PLAYING");
     
            input.close();
     
        } // end method main()
    I don't understand why the arrays rankstr[] and suitstr[] are required in the main() method. Those characteristics belong to PlayingCard and if passed should be passed to the PlayingCard() constructor when a deck is built.

    As suggested above, the shuffle() in the main() method should be deleted. The deck should be shuffled during game play. There are multiple shuffles in the gamePlay() method when I think there should be only one. I digress: I disagree with the instructor's suggestion for shuffling the deck, because it's not a particularly effective approach. It is more effective to NOT shuffle at all and to deal randomly from a deck that has cards in any order:
        // method deal() selects a card randomly that has not been previously dealt,
        // swaps that card with the last card in the deck, and decrements the
        // pointer to the top of the deck 
        public PlayingCard deal()
        {
            int dealIndex = random.nextInt( indexOfTop + 1 );
     
            // this is a test statement to show the card being returned
            System.out.println( "returning card at index " + dealIndex 
                    + " = " + cards[dealIndex] );
     
            // capture the chosen card
            PlayingCard cardToReturn = cards[dealIndex];
     
            // swap the last available card with the chosen card
            cards[dealIndex] = cards[indexOfTop];
     
            // move the chosen card to the first not available card in the deck
            cards[indexOfTop--] = cardToReturn;
     
            // return the randomly chosen card
            return cardToReturn;
        }
    There's a String method called equalsIgnoreCase() that simplifies expressions like these:
    while(response.equals("HIT")||response.equals("hit "))

    The gamePlay() method shouldn't have to initialize or randomize the deck's indices to the rank or the suit. Once the deck is built and shuffled, gamePlay() should get the next card using the DeckOfPlayingCards.deal() method. Once the dealt card is received, gamePlay() finds the card's rank and suit using the PlayingCard .getRank() and .getSuit() methods.

    There is a lot of repetition in gamePlay() that should be broken out into methods.

    The PlayingCard.cardInfo() method indicates a possible misunderstanding of OOP. The cardInfo() method looks like a toString() method (which is what I think the assignment had in mind), and all that would have to be done to correct it is:
        // toString() method. It returns a String that indicates the card's name
        // and suit
        public String toString()
        {
            return rank + "  of  " + suit;
        }

    The current HIT or STAY design is awkward. Instead, consider something like the following:
    // build the user's hand
    do
    {
        // deal two cards, face up and face down to both user and dealer.
        // show user's total, and ask the user if a third or more is desired
    }
    while( hitMe && !busted );
     
    if ( busted )
    {
        // determine if a new game is desired and restart if so
    }
     
    // contine to build the dealer's hand on the two existing cards according to
    // the rules for dealers and evaluate result with each card
    Good luck!

Similar Threads

  1. Need help with fixing this error: ArrayIndexOutOfBoundsException: 1
    By mikuya707 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 13th, 2013, 02:23 PM
  2. Need help fixing
    By brown2292 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: September 12th, 2012, 12:53 PM
  3. help fixing the code of gui
    By aperson in forum AWT / Java Swing
    Replies: 1
    Last Post: January 21st, 2012, 07:20 AM
  4. Help fixing my first program
    By javadude in forum What's Wrong With My Code?
    Replies: 6
    Last Post: January 9th, 2012, 06:52 PM
  5. [SOLVED] Error of "cannot find symbol"
    By big_c in forum File I/O & Other I/O Streams
    Replies: 31
    Last Post: April 9th, 2009, 11:20 AM