Blackjack game - How to use the getter and the toString() methods - java

I'm trying to learn Java and I copied a program that simulate a blackjack game (from here: https://www.youtube.com/watch?v=buGFs1aQgaY).
I understood most of it but I got stuck at how the program make the sum of an hand. In the forth class, called "Player", at some point there is:
cardNum = this.hand[c].getNumber();
Let's say that:
this.hand[c] = King of Clubs.
I don't understand how the program gives as a result:
cardNum = 13.
How does the getNumber method works? (The method is made in the first class, called Card)
I'll post all the classes of the program.
FIRST CLASS.
public class Card {
private Suit mySuit;
private int myNumber;
public Card(Suit aSuit, int aNumber){
this.mySuit = aSuit;
if (aNumber >= 1 && aNumber <= 13){
this.myNumber = aNumber;
} else{
System.err.println(aNumber + " is not a valid Card number");
System.exit(1);
}}
public int getNumber(){
return myNumber;
}
public String toString(){
String numStr = "Err";
switch(this.myNumber){
case 2:
numStr = "Two";
break;
case 3:
numStr = "Three";
break;
case 4:
numStr = "Four";
break;
case 5:
numStr = "Five";
break;
case 6:
numStr = "Six";
break;
case 7:
numStr = "Seven";
break;
case 8:
numStr = "Eight";
break;
case 9:
numStr = "Nine";
break;
case 10:
numStr = "Ten";
break;
case 11:
numStr = "Jack";
break;
case 12:
numStr = "Queen";
break;
case 13:
numStr = "King";
break;
case 1:
numStr = "Ace";
break;
}
return numStr + " of " + mySuit.toString();
}
}
SECOND CLASS
public enum Suit {
Clubs,
Diamonds,
Spades,
Hearts
}
THIRD CLASS
import java.util.Random;
public class Deck {
private Card[] myCards;
private int numCards;
public Deck(){
this(1,false);
}
public Deck(int numDecks, boolean shuffle) {
this.numCards = numDecks * 52;
this.myCards = new Card[this.numCards];
int c = 0;
for (int d = 0; d < numDecks; d++) {
for (int s = 0; s < 4; s++) {
for (int n = 1; n <= 13; n++) {
this.myCards[c] = new Card(Suit.values()[s], n);
c++;
}
}
}
if (shuffle) {
this.shuffle();
}
}
public void shuffle(){
Random rng = new Random();
Card temp;
int j;
for (int i = 0; i < this.numCards; i++){
j = rng.nextInt(this.numCards);
temp = this.myCards[i];
this.myCards[i] = this.myCards[j];
this.myCards[j] = temp;
}
}
public Card dealNextCard() {
Card top = this.myCards[0];
for (int c = 1; c < this.numCards; c++) {
this.myCards[c - 1] = this.myCards[c];
}
this.myCards[this.numCards - 1] = null;
this.numCards--;
return top;
}
public void printDeck(int numToPrint){
for(int c=0; c < numToPrint; c++) {
System.out.printf("% 3d/%d/%s\n", c + 1, this.numCards,
this.myCards[c].toString());
}
System.out.printf("/t/t[%d other]\n", this.numCards-numToPrint);
}
}
FORTH CLASS
public class Player {
private String name;
private Card[]hand = new Card[10];
private int numCards;
public Player(String aName) {
this.name = aName;
this.emptyHand();
}
public void emptyHand(){
for(int c=0; c<10; c++){
this.hand[c] = null;
}
this.numCards = 0;
}
public boolean addCard(Card aCard) {
if (this.numCards == 10) {
System.err.printf("%s's hand already has 10 cards;" +
"cannot add another\n", this.name);
System.exit(1);
}
this.hand[this.numCards] = aCard;
this.numCards++;
return(this.getHandSum()<= 21);
}
public int getHandSum(){
int handSum = 0;
int cardNum;
int numAces = 0;
for(int c=0; c < this.numCards; c++) {
cardNum = this.hand[c].getNumber();
if (cardNum == 1) {
numAces++;
handSum += 11;
} else if (cardNum > 10) {
handSum += 10;
} else {
handSum += cardNum;
}
}
while (handSum >21 && numAces > 0){
handSum -= 10;
numAces--;
}
return handSum;
}
public void printHand(boolean showFirstCard){
System.out.printf("%s's cards:\n", this.name);
for(int c=0; c<this.numCards; c++) {
if(c==0 && !showFirstCard) {
System.out.println(" [hidden]");
} else {
System.out.printf(" %s\n", this.hand[c].toString());
}
}
}
}
FIFTH CLASS - PROGRAM
import java.util.Scanner;
public class GameRunner{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Deck theDeck = new Deck(1, true);
theDeck.printDeck(52);
Player me = new Player("Player 1");
Player dealer = new Player("Dealer");
me.addCard(theDeck.dealNextCard());
dealer.addCard(theDeck.dealNextCard());
me.addCard(theDeck.dealNextCard());
dealer.addCard(theDeck.dealNextCard());
System.out.println("Cards are dealt\n");
me.printHand(true);
dealer.printHand(false);
System.out.println("\n");
boolean meDone = false;
boolean dealerDone = false;
String ans;
while(!meDone || !dealerDone) {
if(!meDone){
System.out.println("Hit or Stay? (Enter H or S):");
ans = sc.next();
System.out.println();
if(ans.compareToIgnoreCase("H") == 0) {
meDone = !me.addCard(theDeck.dealNextCard());
me.printHand(true);
} else {
meDone = true;
}
}
if(!dealerDone){
if (dealer.getHandSum() < 17) {
System.out.println("The Dealer hits\n");
dealerDone = !dealer.addCard(theDeck.dealNextCard());
dealer.printHand(false);
} else {
System.out.println("The Dealer stays\n");
dealerDone = true;
}
}
System.out.println();
}
sc.close();
me.printHand(true);
dealer.printHand(true);
int mySum = me.getHandSum();
int dealerSum = dealer.getHandSum();
if(mySum > dealerSum && mySum <= 21 || dealerSum>21) {
System.out.println("Your win");
} else{
System.out.println("Dealer wins!");
}
}
}

When you create each instance of class Card, you pass in a Suit and a VALUE for that card:
... = new Card(Suit.values()[s], n);
In the above example from the code, the n variable is the value of the card, and was going from 1 to 13 because of the for loops setup to create the decks of cards.
In the Constructor for class Card, we then store that value in the private member called myNumber seen below:
public class Card {
private Suit mySuit;
private int myNumber; // <-- the value of the card is stored here
public Card(Suit aSuit, int aNumber){
// ... other code ...
this.myNumber = aNumber; // <-- store the passed in value in the instance member
// ... other code ...
}
}
Finally, the getNumber() function simply returns the stored value of the card, previously put into myNumber:
public int getNumber(){
return myNumber;
}

Related

Build Blackjack program in Java, but "split" method would require rewriting whole program?

Getting back into programming after many years, and build a simple "blackjack" program in Java.
I'm wondering if the way I structured the methods/objects is bad, using global static variables. The program seems to work fine, but there's no way to implement a "split" method without re-writing everything, since you can't pass the new "split" hands into the "hit" or "stand" functions.
I'm curious how others would structure this and what the flaws in my methodology were. Thanks!
import java.io.*;
import java.util.*;
public class BlackJack {
static int bankroll = 0;
static int bet = 1;
static int index = 0;
static CardDeck d = new CardDeck();
static ArrayList<Card> playerCards = new ArrayList<Card>();
static ArrayList<Card> playerCards2 = new ArrayList<Card>(); //unused - was thinking of using for splitting
static ArrayList<Card> playerCards3 = new ArrayList<Card>(); //unused - was thinking of using for splitting
static ArrayList<Card> playerCards4 = new ArrayList<Card>(); //unused - was thinking of using for splitting
static ArrayList<Card> playerCards5 = new ArrayList<Card>(); //unused - was thinking of using for splitting
static ArrayList<Card> playerCards6 = new ArrayList<Card>(); //unused - was thinking of using for splitting
static ArrayList<Card> dealerCards = new ArrayList<Card>(); //unused - was thinking of using for splitting
static int playerScore = 0;
static int dealerScore = 0;
static String action = "";
static Scanner s = new Scanner(System.in);
public static void main(String[] args) {
initializeBankroll();
while (bet != 0) {
startRound();
display();
if(checkBlackJacks()) continue;
while (playerScore <= 21) {
System.out.println("H - hit, S - stand, X - surrender, D - double down");
action = s.nextLine();
if (action.equals("H")) hit();
else if (action.equals("S")) {
stand();
break;
}
else if (action.equals("X")) surrender();
else if (action.equals("D")) {
doubleDown();
break;
}
}
eval();
}
}
public static int score (ArrayList<Card> list) {
int ret = 0;
int acecounter = 0;
for (int i=0; i<list.size(); i++) {
if (list.get(i).getVal()>1) {
ret += Math.min(10, list.get(i).getVal());
}
else { //An ace
ret += 11;
acecounter++;
}
}
while(ret >21 && acecounter >0) {
ret -= 10;
acecounter -= 1;
}
return ret;
}
public static void dealToPlayer() {
playerCards.add(d.getCard(index));
index++;
}
public static void dealToDealer() {
dealerCards.add(d.getCard(index));
index++;
}
public static void display() {
System.out.println("PLAYER CARDS:");
String playerCardString = "";
for (int i=0; i<playerCards.size(); i++) {
playerCardString += playerCards.get(i).toString();
playerCardString += " ";
}
System.out.println(playerCardString);
System.out.println("DEALER CARD:");
System.out.println(dealerCards.get(0).toString());
}
public static void hit() {
dealToPlayer();
reScore();
display();
}
public static void surrender() {
if(playerCards.size()>2) {
System.out.println("You can't do that");
return;
}
bankroll -= (bet / 2);
playerScore = 100; //surrender
}
public static void reScore() {
playerScore = score(playerCards);
dealerScore = score(dealerCards);
}
public static void stand() {
try {
System.out.println("DEALER DOWNCARD: " + dealerCards.get(1).toString());
Thread.sleep(1000);
while (dealerScore <17) {
dealToDealer();
System.out.println(dealerCards.get(dealerCards.size()-1).toString());
reScore();
System.out.println("DEALER SCORE " + Integer.toString(dealerScore));
Thread.sleep(1000);
}
}catch(Exception E) {
System.out.println("Exception");
}
}
public static void doubleDown() {
if(playerCards.size()>2) {
System.out.println("You can't do that, hitting instead");
hit();
if(playerScore<=21) stand();
return;
}
if( bet * 2 > bankroll) {
System.out.println("Doubling for less...");
bet = bankroll;
hit();
if(playerScore<=21) stand();
return;
}
bet *= 2;
hit();
if(playerScore<=21) stand();
}
public static void split(ArrayList<Card> splitarray, int splitcount) { //INCOMPLETE. How to get this to work?
if(splitarray.size()>2 || bet * (splitcount+1) > bankroll || splitarray.get(1).getVal() != splitarray.get(0).getVal()) {
System.out.println("Can't split. Hitting instead");
hit();
}
ArrayList<Card> s1 = new ArrayList<Card>();
ArrayList<Card> s2 = new ArrayList<Card>();
s1.add(splitarray.get(0));
s2.add(splitarray.get(1));
}
public static void eval() {
if (playerScore==100) { //indicates a surrender, and bankroll has already been adjusted
return;
}
if (playerScore>21) {
System.out.println("BUST");
bankroll -= bet;
return;
}
if (dealerScore>21) {
System.out.println("DEALER BUST");
bankroll += bet;
return;
}
if (playerScore > dealerScore) {
System.out.println("WIN");
bankroll += bet;
return;
}
if (playerScore < dealerScore) {
System.out.println("LOSE");
bankroll -= bet;
return;
}
System.out.println("PUSH");
return;
}
public static void newhand() {
d.shuffle();
playerCards.clear();
dealerCards.clear();
index = 0;
reScore();
}
public static boolean checkBlackJacks() {
if(playerScore == 21) {
if(dealerCards.get(0).getVal()==1) {
System.out.println("Even money? Y / N");
String even = s.nextLine();
if (even=="Y"){
bankroll += bet;
newhand();
return true;
}
}
if(dealerScore != 21) {
System.out.println("BlackJack");
bankroll += (1.5 * bet);
newhand();
return true;
}
else {
System.out.println("Push - Mutual Blackjack");
newhand();
return true;
}
}
if(dealerCards.get(0).getVal()==1) { //insurance
System.out.println("Insurance? Type wager or 0, up to half your bet");
int insuranceBet = s.nextInt();
if (insuranceBet > bankroll) insuranceBet = bankroll;
if (insuranceBet > (bet / 2)) insuranceBet = bet / 2;
if (dealerScore == 21) bankroll += (insuranceBet * 2);
else bankroll -= insuranceBet;
}
if(dealerScore==21) {
System.out.println("Dealer Blackjack");
bankroll -= bet;
newhand();
return true;
}
return false;
}
public static void initializeBankroll() {
System.out.println("Enter your buy-in");
bankroll = s.nextInt();
}
public static void startRound() {
newhand();
System.out.println("Money remaining:" + Integer.toString(bankroll));
System.out.println("Enter your bet");
bet = s.nextInt();
if (bet>bankroll) bet=0;
dealToPlayer();
dealToDealer();
dealToPlayer();
dealToDealer();
reScore();
}
}
___________________
public class Card {
int val; //1 = Ace, 11 = Jack, 12 = Queen, 13 = King
int suit; //1 = Club, 2 = Diamond, 3 = Heart, 4 = Spade
public Card() {
this(1,1);
}
public Card(int val, int suit) {
this.val = val;
this.suit = suit;
}
public int getSuit(){
return suit;
}
public int getVal() {
return val;
}
public void setVal(int a) {
if(a>=1 && a<= 13) val = a;
}
public void setSuit(int a) {
if (a>=1 && a<=4) suit = a;
}
public String toString() {
String valString = "";
String suitString = "";
String ret = "";
switch(val) {
case 1: valString = "A"; break;
case 10: valString = "T"; break;
case 11: valString = "J"; break;
case 12: valString = "Q"; break;
case 13: valString = "K"; break;
default: valString = Integer.toString(val);
}
switch(suit) {
case 1: suitString = "c"; break;
case 2: suitString = "d"; break;
case 3: suitString = "h"; break;
case 4: suitString = "s"; break;
default: suitString = "ERROR"; break;
}
ret = valString + suitString;
return ret;
}
}
______________________
public class CardDeck{
Card[] deck;
public CardDeck(){
int k=0;
deck = new Card[52];
for (int i=0; i<13; i++){
for (int j=0; j<4; j++){
Card c = new Card(i+1,j+1);
deck[k]=c;
k++;
}
}
shuffle();
}
public void shuffle(){
Card[] deckCopy = new Card[52];
boolean[] flags = new boolean[52];
for (int i=0; i<flags.length; i++) flags[i]=false;
int numConverted=0;
while(numConverted<52){
int num = (int)(Math.random() * 52);
if (flags[num]==false){
deckCopy[numConverted]=deck[num];
numConverted++;
flags[num]=true;
}
}
deck = deckCopy;
} //end shuffle
public String toString() {
String ret = "";
for (int i = 0; i<deck.length; i++) {
ret += deck[i].toString();
ret += " ";
}
return ret;
}
public Card getCard(int a) {
if (a<0 || a > 51) return null;
else return deck[a];
}
public int getSuit(int a) {
if (a<0 || a > 51) return 0;
else return deck[a].getSuit();
}
public int getVal(int a) {
if (a<0 || a > 51) return 0;
else return deck[a].getVal();
}
}

How to Collect all scores in Blackjack and record games in a table in java?

I need help with creating a table in for my blackjack, that records all games and also shows the average score of all games.I Have my code but im stuck on what to do to fix the code. Here are all the codes that im working with. Here is an example of what the output should look like:Pic of how output should look like
import java.util.*;
class Blackjack{
public static void main (String[] arg) {
Deck d = new Deck(); d.shuffle();
Hand h = new Hand();
//Score s = new Score(); //added for bonus
System.out.println(d);
System.out.println(d.hit());
System.out.println( d.decode(d.hit()) );
h.add(5);
h.add(10);
System.out.println(h.display());
while(true) {
System.out.print("Enter (n)ew hand, (h)it, or (q)uit: ");
Scanner scan = new Scanner (System.in);
// these variables are for collecting the information for the Score
int [] line = new int [5]; //added for Bonus
int handScore = 0; //added for Bonus
char c = scan.next().charAt(0);
if (c == 'n' || c == 'N') {
System.out.println(c);
h.reset();
if (d.currentIndex < 51){
int card= d.hit(); h.add(card);
card= d.hit(); h.add(card);
h.display();
System.out.println();
} else if (d.currentIndex > 51) {
System.out.println("--- NO CARDS LEFT ON DECK ---");
System.out.println();
break;
} else {
System.out.println("-- NOT ENOUGH CARDS LEFT ON DECK--");
System.out.println();
break;
}
} else if (c == 'h' || c == 'H') {
System.out.println(c);
if (d.currentIndex < 52){ //must be 52
int handValue = h.scoreInHand() ;
if (handValue > 21) { //already busted
System.out.println("--- GET A NEW HAND --- ");
System.out.println();
} else if (handValue == 21) {//already blackjack
System.out.println("--- BlackJack --- ");
System.out.println();
} else if (h.firstIndex > 4 ) {
System.out.println( "-- ALREADY 5 CARDS IN HAND ---");
h.display();
System.out.println( "--- GET A NEW HAND ---");
System.out.println();
} else if (h.firstIndex == 0) {
System.out.println("--- GET A NEW HAND FIRST ---");
System.out.println();
} else {
int card= d.hit(); h.add(card);
h.display(); System.out.println();
}
} else { // > or = 52
System.out.println("----- NO CARDS LEFT ON DECK -----");
System.out.println();
break;
}//end if (d.firstIndex < 52
} else if (c == 'q' || c == 'Q') {
System.out.println(c);
//same as the if(c == n), so it can collect the last game.
break;
}
} //while
//prints the scores of the games the user played while the game was run.
//System.out.print(s.display());System.out.println(); //added for Bonus
System.out.println("BYE!");
}//end main
}
class Hand{
private int []Hand;
public int firstIndex;
Hand(){
Hand=new int[5];
for (int i=0; i<Hand.length; i++)
Hand[i]=-1;
firstIndex=0;
}
public String display(){
String s="";
String empty="Hand is empty";
for (int i=0; i<firstIndex;i++)
s=s+" "+decode(Hand[i]);
if (s.length()==0)
s= empty;
String sih="";
int sihand= scoreInHand();
if(sihand>0&&sihand<21)
sih=""+sihand;
else if(sihand==21&&firstIndex==2)
sih="blackjack";
else if (sihand==21&&firstIndex>2)
sih=""+sihand;
else
sih="BUST";
System.out.println(s+"\n"+sih);
return s.trim();
}
public void reset(){
for (int i=0; i<Hand.length;i++)
Hand[i]=-1;
firstIndex=0;
}
public void add(int card){
Hand[firstIndex]=card;
firstIndex++;
}
public String decode2(int value){
String code=""+"HCDS".charAt(value/13)
+"23456789TJQA".charAt(value%13);
return code;
}
public String decode(int value){
String[] pattern={"Heart","Clubs","Diamond","Spades"};
String[] num={"two","three","four","five","six","seven","eight","nine","ten","jack","queen","king","ace"};
return num[value%13]+ " of " + pattern[value/13];
}
public int scoreInHand(){
int[] s={2,3,4,5,6,7,8,9,10,10,10,10};
boolean firstAce=true;
int value=0;
int sum=0;
for (int i=0; i<firstIndex; i++)
{
value=Hand[i]%13;
if (value==12)
{
if (firstAce)
{
value=11;
firstAce=false;
}
else
value=1;
}
else
value=s[value];
sum=sum+value;
}
return sum;
}
public String toString{
String s="";
for (int i=0; i<5; i++)
{
if (i<firstIndex)
s=s+" | " + decode2(Hand[i])+" ";
else
s=s+" ";
}
s=s+firstIndex;
return s;
}
}//(2,3,4,5,6,7,8,9,10,10,10,10,11)
class Deck{
private int[] cards;
public int currentIndex;
Deck(){
currentIndex=0;
cards=new int[52];
for (int i=0; i<cards.length; i++)
cards[i]=i;
}
public String toString(){
String s="";
for (int i=currentIndex;i<cards.length; i++)
{
/* s=s+" "+cards[i];*/
String code=decode(cards[i]);
s=s+" "+code;
}
return s;
}
public String decode(int value)
{
String code=""+"HCDS".charAt (value/13)
+"23456789TJQKA".charAt(value%13);
return code;
}
public void shuffle(){
int j=0;
for (int i=0;i<cards.length; i++)
{
j=(int)(52*Math.random());
swap(i,j);
}
}
public void swap(int i, int j){
int temp=cards[i];
cards[i]=cards[j];
cards[j]=temp;
}
public int hit(){
int i=cards[currentIndex];
currentIndex++;
return i;
}
}
class Score extends Deck{
private String [] cuts=new String [26];
private int gfirstIndex;
Score(){
cuts=new String[26];
gfirstIndex=0;
}
public void markScore(Hand h, int score)
{
String s="";
char fi;
String hand=h.toString();
int firstIndex;
fi=hand.charAt(hand.length()-1);
firstIndex=fi-'0';
hand=hand.substring(0,hand.length()-1);
s=s+" | "+(gfirstIndex+1)+(((gfirstIndex+1)<10)?" ":" ")|;
s=s+hand+" ";
s=s+"(score="+score+")";
if (score>21)
s=s+"(BUSTS)";
else if (score==21&&firstIndex==2)
s=s+"(BLACKJACK)";
cuts[gfirstIndex]=s;
gfirstIndex++;
}
}

How can I check for duplicate values without making an array?

I have a program that deals 20 cards based on the value of random numbers. So far it works to deal cards such as King of Spades, 2 of Hearts, etc. My job is to check whether or not the cards are duplicate using a method, but without an array. Here is my solution to checking duplicates which doesn't work for obvious reasons:
public class Driver {
public static void main(String [] args) {
for (int i = 0; i < 20; i++){
Cards card1 = new Cards();
Cards card2 = card1;
if (card1 == card2) {
card1 = new Cards();
}
System.out.println(card1);
}
}
}
Here is my support class:
import java.util.Random;
public class Cards {
String hearts = "Hearts";
String diamonds = "Diamonds";
String clubs = "Clubs";
String spades = "Spades";
String suit;
int cardNumber;
String numberName;
String suitName;
Random randomNum = new Random();
public Cards () {
}
public String suit() {
int theRandom = randomNum.nextInt(4);
if (theRandom == 0 ) {
suitName = "hearts";
}
else if ( theRandom == 1) {
suitName = "diamonds";
}
else if (theRandom == 2) {
suitName = "clubs";
}
else {
suitName = "spades";
}
return suitName;
}
public String number() {
int theRandomNum = randomNum.nextInt(12 + 1);
if ( theRandomNum == 1 ) {
numberName = "Ace";
}
else if ( theRandomNum == 2) {
numberName = "2";
}
else if ( theRandomNum == 3) {
numberName = "3";
}
else if ( theRandomNum == 4) {
numberName = "4";
}
else if ( theRandomNum == 5) {
numberName = "5";
}
else if ( theRandomNum == 6) {
numberName = "6";
}
else if ( theRandomNum == 7) {
numberName = "7";
}
else if ( theRandomNum == 8) {
numberName = "8";
}
else if ( theRandomNum == 9) {
numberName = "9";
}
else if ( theRandomNum == 10) {
numberName = "10";
}
else if ( theRandomNum == 11) {
numberName = "Jack";
}
else if ( theRandomNum == 12) {
numberName = "Queen";
}
else if ( theRandomNum == 13) {
numberName = "King";
}
return numberName;
}
public String toString()
{
if (number() == "null") {
return ("3" + " of " + suit());
}
return (number() + " of " + suit());
}
}
For using a large String to store the cards that have been chosen:
String cards = "";
for(int i = 0; i < 20; i++)
{
Cards card = new Cards();
while(cards.contains(card.toString()))
card = new Cards(); //keep generating a random card until it's a new card
cards += card.toString(); //add the card to the string of cards
System.out.println(card);
}
This code would go inside the main method of your Driver class
First your code has a small mistake
int theRandomNum = randomNum.nextInt(12 + 1)
while, determining from your following code you actually mean
int theRandomNum = randomNum.nextInt(12)+1
To store what cards you already had, you can just introduce a String and fill it step by step, always testing if the card you want to accept is not already contained in this String.
//This goes above the loop where you create your cards
String cards = "";
//This goes into the loop
while(cards.contains(card1.toString()){
card1 = new Cards();
}
cards += card1.toString() + "#"; //Using # as a delimiter
System.out.println(card1);
//At the end you could also print your set of cards
System.out.println(cards);
It's not a very nice approach because you're not permitted to use arrays or similar structures but should do its work.
Please also keep in mind that class names are supposed to be singular. So not Cards but Card.

Looping through array just printing classname#hascode

I am trying to work through an assignment and currently stumped as to what my issue could be. I've read through several post and attempted to resolve without success. I know a lot of my code could be simplified, but this is a progression through the text so a lot of stuff has not yet been covered...
This is my Card class
import java.util.Random;
public class Card {
private int suit,face;
private String cardS,cardF;
// Default constructor to generate random number for face and suit
public Card()
{
Random rand = new Random();
suit = rand.nextInt(4)+1;
face = rand.nextInt(13)+1;
}
// Receive card and suit values
public Card(int cardSuit, int cardFace) {
suit = cardSuit;
face = cardFace;
// Define card face and suit values
if(suit == 1){
cardS = "Clubs";
}
else if(suit == 2){
cardS = "Hearts";
}
else if(suit == 3){
cardS = "Spades";
}
else if(suit == 4){
cardS = "Diamonds";
}
if(face == 1){
cardF = "Ace";
}
else if(face == 2){
cardF = "2";
}
else if(face == 3){
cardF = "3";
}
else if(face == 4){
cardF = "4";
}
else if(face == 5){
cardF = "5";
}
else if(face == 6){
cardF = "6";
}
else if(face == 7){
cardF = "7";
}
else if(face == 8){
cardF = "8";
}
else if(face == 9){
cardF = "9";
}
else if(face == 10){
cardF = "10";
}
else if(face == 11){
cardF = "Jack";
}
else if(face == 12){
cardF = "Queen";
}
else if(face == 13){
cardF = "King";
}
//return cardF + " of " + cardS;
}
// Get numerical face value
public int getNumericFace(){
return face;
}
// Get numerical suit value
public int getNumericSuit(){
return suit;
}
}
This is my DeckOfCards class
public class DeckOfCards {
public static final int MAXDECK = 52;
int remainingDeck,suit,face;
String cardS,cardF;
private int myCard;
int cardIndex;
Card[] cardDeck;
public DeckOfCards() {
cardDeck = new Card[MAXDECK];
// Create array of 52 cards
// outer loop cardSuit
// inner loop cardFace
int index = 0;
int maxSuit = 4;
int maxFace = 13;
for (int cardSuit = 1 ; cardSuit <= maxSuit ; cardSuit++)
{
for (int cardFace = 1 ; cardFace <= maxFace ; cardFace++)
{
cardDeck[index] = new Card(cardSuit,cardFace);
index++;
}
}
}
public String getArray()
{
System.out.println(cardDeck[0]);
for (int i = 0 ; i < cardDeck.length ; i++)
{
System.out.println(cardDeck[i]);
}
return "";
}
public String toString()
{
String deckAsString = "";
int i=0;
for (int s = 1; s <= 4 ; s++)
{
for (int c = 1 ; c <= 13 ; c++ )
{
deckAsString += (cardDeck[i] + "");
i++;
}
deckAsString += "\n";
}
return (deckAsString);
}
}
This is my main class... running both methods here have the issue.
public class MainDeck {
public static void main(String[] args) {
DeckOfCards game = new DeckOfCards();
System.out.println("test getArray method");
System.out.println(game.getArray());
System.out.println("test toString method");
System.out.println(game.toString());
}
}
Thanks for your help!
As your toString method in DeckOfCards is using cardDeck array objects and adding them to the returned String:
deckAsString += (cardDeck[i] + "");
So you need to override toString method in Card class also and use it in string manipulations.
Please implement toString() method in your Card class also.

DeckOfCards and HighLow Class incompatible types

I get an incompatible types error when running my code. It is when "playerGuess = d1.deal();"
Thank you in advanced. This main has two other classes that go along with it. The DeckOfCards and Cards Classes.
Card Class
public class Card
{
public final static int ACE = 1;
public final static int TWO = 2;
public final static int THREE = 3;
public final static int FOUR = 4;
public final static int FIVE = 5;
public final static int SIX = 6;
public final static int SEVEN = 7;
public final static int EIGHT = 8;
public final static int NINE = 9;
public final static int TEN = 10;
public final static int JACK = 11;
public final static int QUEEN = 12;
public final static int KING = 13;
public final static int CLUBS = 1;
public final static int DIAMONDS = 2;
public final static int HEARTS = 3;
public final static int SPADES = 4;
private final static int NUM_FACES = 13;
private final static int NUM_SUITS = 4;
private int face, suit;
private String faceName, suitName;
//-----------------------------------------------------------------
// Creates a random card.
//-----------------------------------------------------------------
public Card()
{
face = (int) (Math.random() * NUM_FACES) + 1;
setFaceName();
suit = (int) (Math.random() * NUM_SUITS) + 1;
setSuitName();
}
//-----------------------------------------------------------------
// Creates a card of the specified suit and face value.
//-----------------------------------------------------------------
public Card(int faceValue, int suitValue)
{
face = faceValue;
setFaceName();
suit = suitValue;
setSuitName();
}
//-----------------------------------------------------------------
// Sets the string representation of the face using its stored
// numeric value.
//-----------------------------------------------------------------
private void setFaceName()
{
switch (face)
{
case ACE:
faceName = "Ace";
break;
case TWO:
faceName = "Two";
break;
case THREE:
faceName = "Three";
break;
case FOUR:
faceName = "Four";
break;
case FIVE:
faceName = "Five";
break;
case SIX:
faceName = "Six";
break;
case SEVEN:
faceName = "Seven";
break;
case EIGHT:
faceName = "Eight";
break;
case NINE:
faceName = "Nine";
break;
case TEN:
faceName = "Ten";
break;
case JACK:
faceName = "Jack";
break;
case QUEEN:
faceName = "Queen";
break;
case KING:
faceName = "King";
break;
}
}
//-----------------------------------------------------------------
// Sets the string representation of the suit using its stored
// numeric value.
//-----------------------------------------------------------------
private void setSuitName()
{
switch (suit)
{
case CLUBS:
suitName = "Clubs";
break;
case DIAMONDS:
suitName = "Diamonds";
break;
case HEARTS:
suitName = "Hearts";
break;
case SPADES:
suitName = "Spades";
break;
}
}
//-----------------------------------------------------------------
// Determines if this card is higher than the passed card. The
// second parameter determines if aces should be considered high
// (beats a King) or low (lowest of all cards). Uses the suit
// if both cards have the same face.
//-----------------------------------------------------------------
public boolean isHigherThan(Card card2, boolean aceHigh)
{
boolean result = false;
if (face == card2.getFace())
{
if (suit > card2.getSuit())
result = true;
}
else
{
if (aceHigh && face == ACE)
result = true;
else
if (face > card2.getFace())
result = true;
}
return result;
}
//-----------------------------------------------------------------
// Determines if this card is higher than the passed card,
// assuming that aces should be considered high.
//-----------------------------------------------------------------
public boolean isHigherThan(Card card2)
{
return isHigherThan(card2, true);
}
//-----------------------------------------------------------------
// Returns the face (numeric value) of this card.
//-----------------------------------------------------------------
public int getFace()
{
return face;
}
//-----------------------------------------------------------------
// Returns the suit (numeric value) of this card.
//-----------------------------------------------------------------
public int getSuit()
{
return suit;
}
//-----------------------------------------------------------------
// Returns the face (string value) of this card.
//-----------------------------------------------------------------
public String getFaceName()
{
return faceName;
}
//-----------------------------------------------------------------
// Returns the suit (string value) of this card.
//-----------------------------------------------------------------
public String getSuitName()
{
return suitName;
}
//-----------------------------------------------------------------
// Returns the string representation of this card, including
// both face and suit.
//-----------------------------------------------------------------
public String toString()
{
return faceName + " of " + suitName;
}
}
Deck of Cards Class
public class DeckOfCards
{
private Card[] myCardDeck;
private int nowCard;
public DeckOfCards( ) {
myCardDeck = new Card[ 52 ];
int i = 0;
for ( int suit = Card.SPADES; suit <= Card.DIAMONDS; suit++ )
for ( int pos = 1; pos <= 13; pos++ )
myCardDeck[i++] = new Card(suit, pos);
nowCard = 0;
}
public void shuffle(int n)
{
int i, j, k;
for ( k = 0; k < n; k++ )
{
i = (int) ( 52 * Math.random() );
j = (int) ( 52 * Math.random() );
Card tmp = myCardDeck[i];
myCardDeck[i] = myCardDeck[j];
myCardDeck[j] = tmp;;
}
nowCard = 0;
}
public Card deal()
{
if ( nowCard < 52 )
{
return ( myCardDeck[ nowCard++ ] );
}
else
{
System.out.println("No Cards BRUH");
return ( null );
}
}
public String toString()
{
String s = "";
int Q = 0;
for ( int i = 0; i < 4; i++ )
{
for ( int j = 1; j <= 13; j++ )
s += (myCardDeck[Q++] + " ");
s += "\n";
}
return ( s );
}
public int deckSize()
{
for(int z =0; z < myCardDeck.length && z < 52; z++);
return myCardDeck.length;
}
}
The main driver class (HighLow)
import java.util.*;
public class HighLow
{
public static void main (String [] args)
{
DeckOfCards d1 = new DeckOfCards();
Scanner scan = new Scanner(System.in);
String playerGuess;
Card firstDeal, secondDeal;
int count =0;
d1.shuffle(1);
firstDeal = d1.deal();
while(true)
{
if(d1.deckSize() == 0);
{
System.out.print("Game over! Score: " + count);
break;
}
System.out.print(firstDeal);
System.out.print("Guess if next card will be a high card, or a low card!");
System.out.print("Use H or L");
playerGuess = d1.deal();
if(secondDeal.isHigherThan(firstDeal)&&playerGuess.equals("H"))
{
System.out.print("Nice!!!!");
count++;
firstDeal=secondDeal;
}
else if(firstDeal.isHigherThan(secondDeal) && playerGuess.equals("L"))
{
System.out.println("NICE!!!!");
count++;
firstDeal = secondDeal;
}
else if (firstDeal.isHigherThan(secondDeal) && playerGuess.equals("L"))
{
System.out.print("Good Job!!!!");
count++;
firstDeal = secondDeal;
}
else
{
System.out.println("Sorry, the game is over. But your score is! " + count);
break;
}
}
}}
Thank you!
The method deal() returns a Card:
public Card deal() { ... }
The variable playerGuess is a String:
String playerGuess;
You can't assign a Card to a String:
playerGuess = d1.deal(); // incompatible types
It looks like you want playerGuess to store the user input, so it should be:
playerGuess = scan.next();

Categories

Resources