I need help drawing a Hand of Cards - java

I am trying to draw a Hand of Cards (in the Hand class) but have it shuffled. My problem is if I do shuffleDeck() in the initialDeal() method (where I need to draw a Hand of Cards but shuffled) it gives me an ArrayIndexOutOfBounds exception.
And I draw two narfs OF Clubs... Note, the narf is basically 0 and just a placeholder. It will not be used.
class Card {
int suit, rank;
public Card () {
this.suit = 0; this.rank = 0;
}
public Card (int suit, int rank) {
this.suit = suit; this.rank = rank;
}
public int getSuit() {
return suit;
}
public int getRank() {
return rank;
}
public void printCard () {
String[] suits = { "Clubs", "Diamonds", "Hearts", "Spades" };
String[] ranks = { "narf", "Ace", "2", "3", "4", "5", "6",
"7", "8", "9", "10", "Jack", "Queen", "King" };
System.out.println (ranks[rank] + " of " + suits[suit]);
} //end printCard
} //end class
Card class(this is basically doing basic stuff) ^
import java.util.Random;
class Hand {
static Card[] deck = new Card[52];
Card[] hand = new Card[10];
static int index;
public static void createDeck () {
int m = 0;
for (int j = 0; j < 4; j++) {
for (int k = 1; k < 14; k++) {
deck[m] = new Card(j,k);
m++;
}
}
index = 0;
} // end createDeck
public static Card deal () {
Hand.index++;
return deck[index-1];
} // end deal
public static int compareCard (Card c1, Card c2) {
if (c1.getSuit() > c2.getSuit()) return 1;
if (c1.getSuit() < c2.getSuit()) return -1;
if (c1.getRank() > c2.getRank()) return 1;
if (c1.getRank() < c2.getRank()) return -1;
return 0;
} // end compareCard
public void printDeck (int size) {
int j = 0;
while (j < size) {
deck[j].printCard();
j++;
}
}// end printDeck
public static void shuffleDeck () {
Card tempCard;
Random rd = new Random();
for (index = 0; index < deck.length; index++) {
int r = rd.nextInt(deck.length);
tempCard = deck[index];
deck[index] = deck[r];
deck[r] = tempCard;
}
} // end shuffleDeck
public void initialDeal() {
hand[0] = null;
hand[1] = null;
hand[0] = deal();
hand[1] = deal();
}
public void printHand() {
initialDeal();
index = 0;
for(Card outputCard = new Card(); hand[index] != null; index++) {
outputCard.printCard();
}
}
}
Hand class^ (this is where I need to draw two cards from a shuffled deck)
class Dealer {
Hand dealer = new Hand();
public Dealer () {
dealer.createDeck();
dealer.shuffleDeck();
System.out.println("Dealer's Hand");
System.out.println("");
initDeal();
}
public void initDeal() {
dealer.initialDeal();
dealer.printHand();
}
} //end class
Dealer class.^ Calling the methods of Hand
class Driver {
public static void main (String[] args) {
Dealer dealer = new Dealer();
} //end main method
} //end class
^ Running everything basically

You're modifying the index in shuffleDeck, so after the shuffleDeck finishes, the index is shuffleDeck.length.
In shuffleDeck, do for (int index = 0; index < deck.length; index++)
(note the int index -> declare local variable, and not use the static one.)
Or you can (in initialDeal) set the index to 0.

Related

How do I transfer the existing String array to 2D array

I am trying to get my private void transfer method and pass it into a 2D array transfer2D method, after which I am able to print it out using the print2D_1 method. I am also trying to sort the array from the highest suit to the lowest suit followed by the highest rank to the lowest rank e.g. S12, S9, H13, D09, C10. Please advice.
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
enum SuitEnum
{
Spade ('S'),
Heart ('H'),
Diamond ('D'),
Club ('C');
public char suit;
SuitEnum(char suit)
{
this.suit = suit;
}
// Accessor getter
public char getSuit ()
{
return suit;
}
}
enum RankEnum
{
Two ('2'),
Three ('3'),
Four ('4'),
Five ('5'),
Six ('6'),
Seven ('7'),
Eight ('8'),
Nine ('9'),
Ten ('T'),
Jack ('J'),
Queen ('Q'),
King ('K'),
Ace ('A');
public char rank;
RankEnum(char rank)
{
this.rank = rank;
}
// Acessor getter
public char getRank ()
{
return rank;
}
}
class PlayingCard
{
private SuitEnum suit;
private RankEnum rank;
private PlayingCard pc;
//constructor
public PlayingCard(SuitEnum suit, RankEnum rank)
{
this.suit = suit;
this.rank = rank;
}
//copy constructor
public PlayingCard(PlayingCard pc)
{
this.pc = pc;
}
//accessor get method
public SuitEnum getSuit()
{
return suit;
}
public RankEnum getRank()
{
return rank;
}
//setter
public void setCard(SuitEnum suit, RankEnum rank)
{
this.suit = suit;
this.rank = rank;
}
#Override
public String toString()
{
return String.format("%3s%s",suit.getSuit(),rank.getRank());
}
}
class ChuaWeiheng_A1
{
private final int MAXC = 13;
private final int MAXD = 52;
private void deckOfCards(ArrayList<PlayingCard> values)
{
for (SuitEnum suit : SuitEnum.values())
{
for (RankEnum rank: RankEnum.values())
values.add(new PlayingCard (suit, rank));
}
}
private void printDeck(ArrayList<PlayingCard>values)
{
int count = 0;
System.out.println("Printing from ArrayList");
System.out.println();
{
for (PlayingCard s : values)
{
count++;
System.out.print(s);
if (count == MAXC)
{
System.out.println();
count = 0;
}
}
}
System.out.println("-------------------------");
}
private void listToArray(ArrayList<PlayingCard> values, PlayingCard[] valuesArray)
{
int i = 0;
for (PlayingCard s: values)
{
valuesArray [i] = s;
++i;
}
}
private void printDeck(PlayingCard[] valuesArray)
{
int count = 0;
System.out.println("Printing from Array");
System.out.println();
for (PlayingCard s : valuesArray)
{
count++;
System.out.print(s);
if (count == MAXC)
{
System.out.println();
count = 0;
}
}
System.out.println("-------------------------");
}
private void transfer(PlayingCard[] cardArray, String[] strArray)
{
String[] arrayNo = new String[]{"02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14"};
String[] arrayLetter = new String[]{"Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace"};
int i = 0;
for (PlayingCard s : cardArray)
{
String currentCard = s.getRank().toString();
for (int j = 0; j < 13; j++)
{
if (currentCard.equals(arrayLetter[j]))
{
strArray[i] = s.getSuit().toString().charAt(0) + arrayNo[j];
}
}
i++;
}
}
private void printStringArray(String[] strArray)
{
int count = 0;
System.out.println("Printing from string array");
System.out.println();
for (int i = 0; i < MAXD; i++)
{
count++;
System.out.print(" " + strArray[i]);
if (count == MAXC)
{
System.out.println();
count = 0;
}
}
System.out.println("-------------------------");
}
// shuffle
private void shuffle(PlayingCard[] valuesArray)
{
Random random = ThreadLocalRandom.current();
int count = 0;
for (int k = valuesArray.length -1; k> 0; k --)
{
int i = random.nextInt(k+1);
PlayingCard j = valuesArray[i];
valuesArray[i] = valuesArray[k];
valuesArray[k] = j;
}
System.out.println("Shuffle the cards - Array Version");
System.out.println("Printing from array");
System.out.println();
{
for (PlayingCard s : valuesArray)
{
count++;
System.out.print(s);
if (count == MAXC)
{
System.out.println();
count = 0;
}
}
System.out.println("-------------------------");
}
}
private void transfer2D(String[][] twoD, String[] strArray)
{
int rows = 4;
int columns = 13;
twoD = new String[rows][columns];
for(int i = 0; i < twoD.rows; i++)
{
for(int j = 0; j < twoD.columns; j++)
{
twoD[i][j] = strArray[(i*twoD.columns)+j];
}
}
}
private void print2D_1(String[][] twoD)
{
int count = 0;
System.out.println("Printing from string array");
System.out.println();
for(int[] a : twoD)
{
for(int i : a)
{
}
}
}
public static void main(String[] args)
{
ArrayList<PlayingCard>X = new ArrayList<PlayingCard> ();
ChuaWeiheng_A1 T1 = new ChuaWeiheng_A1();
PlayingCard [] T2 = new PlayingCard[T1.MAXD];
String[] strArr = new String[52];
T1.deckOfCards(X);
T1.printDeck(X);
T1.listToArray(X,T2);
T1.printDeck(T2);
T1.shuffle(T2);
T1.transfer(T2, strArr);
T1.printStringArray(strArr);
}
}
Your transfer2D() method should look like this:
private void transfer2D(String[] strArray, String[][] twoD)
{
int i = 0;
for( int suit = 0; suit < 4; suit++ )
for( int rank = 0; rank < 13; rank++ )
twoD[suit][rank] = strArray[i++];
}
as a convention: outgoing values should appear at the end of the parameter list

deck of cards using methods and multiple classes

I'm getting no output and not sure where to go from here.
Design and implement a class called Card, which represents a standard playing card. Each card has a suit and a face value. Then, create a driver class that stores 52 objects of the Card class into an array. Include methods to shuffle the deck, deal a card and report the number of cards left in the deck. The shuffle method should assume a full deck. Your main method should deal each card from a shuffled deck, printing each card (suit and face value) as it is dealt.
Here's what I have so far:
import java.util.Random;
public class card {
public static void main(String[] args) {}
public class deck {
int[] deck = new int[52];
String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
public void create() {//initialize cards
for (int i = 0; i < deck.length; i++) deck[i] = i;
}
public void shuffle() {//deck shuffle
for (int i = 0; i < deck.length; i++) {
int index = (int) (Math.random() * deck.length);
int temp = deck[i];
deck[i] = deck[index];
deck[index] = temp;
}
//display all the cards!
for (int i = 0; i < deck.length; i++)
{
String suit = suits[deck[i] / 13];
String rank = ranks[deck[i] % 13];
System.out.println("Card number " + deck[i] + ": " + rank + " of " + suit);
}
}
}
}
In java, the method main() is where your code will start running. You have nothing in your main method right now:
public static void main(String[] args) {}
To get it to do something, change it to something like this:
public static void main(String[] args) {
deck myDeck = new deck();
myDeck.create();
myDeck.shuffle();
}
As a note, it is good practice in java to name your classes with capital letters.
Here, I tried to write some code for you, its not complete, but provides a framework for you to continue, all you have to do is implement your own shuffle method and add more variables to ranks:
public class CardDriver {
public static void main(String[] args) {
Deck myDeck = new Deck();
myDeck.shuffle();
System.out.println("Dealt cards are:");
myDeck.dealAllCards();
}
}
class Card {
String suite, faceValue;
Card(String suite, String faceValue) {
this.suite = suite;
this.faceValue = faceValue;
}
void printCard() {
System.out.println(faceValue + " " + suite);
}
}
class Deck {
String[] suits = { "Spades", "Hearts", "Diamonds", "Clubs" };
String[] ranks = { "6", "7" };
int count = ranks.length * suits.length;
Card deck[] = new Card[count];
Deck() { // fills out the deck
int index = 0; // this is for simple deck filling
for (int i = 0; i < ranks.length; i++) { // for ranks
for (int j = 0; j < suits.length; j++) { // for suits
deck[index] = new Card(suits[j], ranks[i]);
index++;
}
}
};
void shuffle() { // shuffles the deck
// your code here
}
Card dealCard() { // gives card from deck
if (returnLeft() > 0) {
count--;
return deck[count];
} else return null;
}
int returnLeft() {
return count;
}
void dealAllCards() {
int counter = count;
for (int i = 0; i < counter; i++) {
Card someCard = dealCard();
someCard.printCard();
}
}
}

Trying to Debug very glitchy blackjack game in java

First, thanks for reading this, I'm going to start by posting all code relevant to the program which you can skim or completely skip over for now.
Try to ignore all my sarcastic comments throughout the code btw they aren't directed at stack overflow :P
BlackJack file:
import java.util.Scanner;
import java.util.InputMismatchException;
public class BlackJack { //i should probably put a betting thing somewhere.....
//also should probably add a thing that tells them one of the dealers cards
//should also put something that stops 2 players from having the same name
static Scanner input = new Scanner(System.in); //honestly have no idea if i can put this here but it seems to work. keyword; seems
//good lucking counting cards with all this shuffling lol
public void absolutelyNothing() { //maybe put a betting method here instead of a method that does nothing???
//Do NOT Delete This Method!
}
public static void displayHands(Hand[] hands, String[] playerNames, int players) {
for (int i = 1; i < players; i++) {
display(hands, playerNames, i);
}
displayDealer(hands);
}
public static void display(Hand[] hands, String[] playerNames, int i) {
System.out.println(playerNames[i] + " has " + hands[i]);
}
public static void displayDealer(Hand[] hands) {
System.out.println("Dealer has " + hands[0].dealerDisplay());
}
public static boolean win(Hand[] hands, int i) {
int value = worth(hands[i]);
int dealer = worth(hands[0]);
if (value == -1) {
return false;
}
if (value > dealer) {
return true;
}
return false;
}
public static void winners(Hand[] hands, String[] playerNames) {
for (int i = 1; i < hands.length; i++) {
if (win(hands, i) == true) {
System.out.println(playerNames[i] + " beat the dealer");
}
else {
System.out.println(playerNames[i] + " lost to the dealer");
}
}
}
public static int worth(Hand hand) {
int sum = 0;
int aces = 0;
for (int i = 0; i < hand.howManyCards(); i++) {
Card card = hand.getCard(i);
int value;
if (card.getNumber() == -10) {
aces++;
value = 11;
}
else {
value = card.getNumber();
}
sum+= value;
}
for (int i = 0; aces > i; i++) {
if (sum >= 22) {
sum = sum - 10;
}
}
if (sum >= 22) {
return -1;
}
return sum;
}
public static void dealerTurn(Deck deck, Hand[] hands) {
int worth = worth(hands[0]);
while (worth < 16) {
dealCard(deck, hands, 0);
}
}
public static void playTurn(Deck deck, Hand[] hands, int i, String[] playerNames) {
// System.out.println(playerNames[i] + " hit?" + " Your hand is worth " + worth(hands[i]) );
boolean hit;
displayHands(hands, playerNames, hands.length);
while (true) {
if (worth(hands[i]) == -1) {
System.out.println("Bust");
break;
}
System.out.println(playerNames[i] + " hit?" + " Your hand is worth " + worth(hands[i]) );
try {
hit = input.nextBoolean();
}
catch (InputMismatchException exception) {
System.out.println("Please enter \"true\" or \"false\"");
continue; //pretty sure this continue is causing the glitch where if you don't enter a boolean it goes insane
}
if (hit == true) {
dealCard(deck, hands, i);
}
else {
break;
}
}
}
public static void everyoneGo(Deck deck, Hand[] hands, int players, String[] playerNames) {
for (int j = 1; j < players + 1; j++) { //players go
playTurn(deck, hands, j, playerNames);
}
dealerTurn(deck, hands);
}
public static Deck newHand(Deck deck) {
Deck newDeck = new Deck();
return newDeck;
}
public static void dealCard(Deck deck, Hand[] hands, int i) {
deck.shuffleDeck();
//goodluck counting cards
hands[i].addCard(deck.getCard(0));
deck.removeCard(0);
}
public static void giveNextCard(Hand[] hands, Deck deck, int i) {
hands[i].addCard(deck.getCard(0));
deck.removeCard(0);
}
public static Hand[] firstTwoCards(int players, String[] playerNames, Deck deck) { //gives dealer cards first an I'm too lazy to fix
deck.shuffleDeck();
//seriously good luck
Hand[] hands = new Hand[players + 1]; //dealer is hands[0]
for (int i = 0; i < players + 1; i++) {
hands[i] = new Hand(playerNames[i]);
}
for (int j = 0; j < 2; j++) {
for (int i = 0; i < players + 1; i++) {
giveNextCard(hands, deck, i);
}
}
return hands;
}
public static String[] getNames(int players) {
System.out.println("What are the names of the players?");
String[] playerNames = new String[players + 1];
playerNames[0] = "Dealer";
for (int i = 1; i < players + 1; i++) {
playerNames[i] = input.next(); //something with this line the last time you use it
}
return playerNames;
}
public static int peoplePlaying() {
System.out.println("How many people are playing?");
int players = input.nextInt();
return players;
}
public static void main(String[] args) {
int players = peoplePlaying();
String[] playerNames = getNames(players);
Deck deck = new Deck();
Hand[] hands = firstTwoCards(players, playerNames, deck);
everyoneGo(deck, hands, players, playerNames);
winners(hands, playerNames);
}
}
//if you're smart you would have realized all this shuffling has absolutely no effect on counting cards lol now figure out why
Hand File:
public class Hand extends CardList {
public Hand(String label) {
super(label);
}
public void display() {
System.out.println(getLabel() + ": ");
for (int i = 0; i < size(); i++) {
System.out.println(getCard(i));
}
System.out.println();
}
}
Deck File:
public class Deck extends CardList {
public Deck(String label) {
super(label);
for (int suit = 0; suit <= 3; suit++) {
for (int rank = 1; rank <= 13; rank++) {
addCard(new Card(rank, suit));
}
}
}
}
Cardlist File:
import java.util.ArrayList;
import java.util.Random;
public class CardList {
public String name;
public ArrayList<Card> cards;
public CardList(String name) {
this.name = name;
this.cards = new ArrayList<Card>();
}
public String toString() {
String s = "";
for (int i = 0; i < cards.size(); i++) {
s = s + cards.get(i) + ", ";
}
return s;
}
public String dealerDisplay() {
return cards.get(0).toString();
}
public String getName() {
return name;
}
public Card getCard(int i) {
return cards.get(i);
}
public int howManyCards() {
return cards.size();
}
public void addCard(Card card) {
cards.add(card);
}
public void removeCard(int i) {
cards.remove(i);
}
public void swapCards(int i, int j) {
Card wait = cards.get(i);
cards.set(i, cards.get(j));
cards.set(j, wait);
}
public void shuffleDeck() {
for (int k = 0; k < 10; k++) { //not sure how well the algorithm works but if you do it 10 times it shouldn't matter how bad it is
for (int i = 0; i < howManyCards(); i++) {
int j = (int) (Math.random() * howManyCards());
swapCards(i, j);
}
}
}
}
and finally the card object:
public class Card {
int number;
int suit;
public static final String[] NUMBERS = {null, null, "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"};
public static final String[] SUITS = {"Diamonds", "Clubs", "Spades", "Hearts"};
public Card(int number, int suit) {
this.number = number;
this.suit = suit;
}
#Override
public String toString() {
return NUMBERS[number] + " of " + SUITS[suit];
}
public int getNumber() {
if (number == 14) { //used to tell if its an ace in blackjack file
return -10;
}
if (number < 11) {
return number;
}
else {
return 10;
}
}
}
Alright so hopefully you didn't kill yourself by attempting to read all of that and I realize my code style/organization could use some work.
Anyways their are a few things that are very weird with the program that I can't seem to figure out. Sometimes the program will run fine and you can play a full game with lots of players but other times it throws a bunch of exceptions.
basically if you bust (go over 21) the program throws this 100% of the time:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at CardList.getCard(CardList.java:31)
at BlackJack.dealCard(BlackJack.java:151)
at BlackJack.dealerTurn(BlackJack.java:93)
at BlackJack.everyoneGo(BlackJack.java:138)
at BlackJack.main(BlackJack.java:209)
btw if someone could explain what it means by exceptions at lines that don't exist such as 653 (the first message) that would be very helpful.
It also throws the same exception some of the time even if you don't bust which I'm assuming is the dealer busting as the dealer plays automatically obeying the regular casino rules for dealers.
If anyone can figure it out it would be greatly appreciated, thanks!

Java Array Index Out of Bounds somehow?

In my game's code, I am trying to add a card to hand. As soon as I do, my array is out of bounds. Everything looks right, but maybe I'm missing something.
FYI, one and two are Player instances. Relevant code from Main class (sorry about the formatting. i suck at transferring it to Stack Overflow):
import java.util.*;
public class Program {
public static void main(String args[]) {
String[] rank = {"two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "jack", "queen", "king", "ace"};
String[] suit = {"hearts", "diamonds", "spades", "clubs"};
Scanner scan = new Scanner(System.in);
String something = "yes", something2 = "yes"; //Use with while loop
String winner = "yes"; //Use for while loop
String temp; //Use with setting names
Card[] deck = new Card[52]; //Deck array
int playercount = 0;
Player one = new Player("temp");
Player two = new Player("temp");
Player three = new Player("temp");
Player four = new Player("temp");
while (something2.equals("yes") || playercount < 2) { //Add players to game
System.out.println("Would a(nother) player like to join?");
something2 = scan.nextLine();
System.out.println();
if (something2.equals("yes")) {
if (playercount <= 4) {
if (playercount == 0) {
System.out.println("What is your name: ");
Player one1 = new Player(scan.nextLine());
one = one1;
playercount++;
System.out.println();
}
else if (playercount == 1) {
System.out.println("What is your name: ");
Player two2 = new Player(scan.nextLine());
two = two2;
playercount++;
System.out.println();
}
else if (playercount == 2) {
System.out.println("What is your name: ");
Player three3 = new Player(scan.nextLine());
three = three3;
playercount++;
System.out.println();
}
else if (playercount == 3) {
System.out.println("What is your name: ");
Player four4 = new Player(scan.nextLine());
four = four4;
playercount++;
System.out.println();
}
else {System.out.println("Only four players are allowed.");
something2 = "no";}
}
}
else if (playercount < 2) {
System.out.println("You need at least two players...");
System.out.println();
}
else something2 = "no";
}
//Start game
while (something.equals("yes")) {
//Prepare game
Card.makeDeck(deck, rank, suit);
deck = Card.getDeck();
Card.shuffle(deck);
deck = Card.getDeck();
//Deal cards
if (playercount == 2) {
for (int i = 1; i < 8; i++) {
one.addCard(Card.draw(deck));
deck = Card.getDeck();
two.addCard(Card.draw(deck));
deck = Card.getDeck();
}
}
else if (playercount == 3) {
for (int i = 1; i < 8; i++) {
one.addCard(Card.draw(deck));
deck = Card.getDeck();
two.addCard(Card.draw(deck));
deck = Card.getDeck();
three.addCard(Card.draw(deck));
deck = Card.getDeck();
}
}
else {
for (int i = 1; i < 8; i++) {
one.addCard(Card.draw(deck));
deck = Card.getDeck();
two.addCard(Card.draw(deck));
deck = Card.getDeck();
three.addCard(Card.draw(deck));
deck = Card.getDeck();
four.addCard(Card.draw(deck));
deck = Card.getDeck();
}
}
}
}
}
Card class:
import java.util.*;
public class Card {
private String suit;
private String rank;
private static int temp = 0, temp2 = 0; //Use for reseting rank and suit
private static Card temp3; //Use for draw method
private static int temp4; //Use for shuffle method
private static Card[] deck = new Card[52];
//Constructors
public Card() {
this.rank = "two";
this.suit = "hearts";
}
public Card(String r, String s) {
this.rank = r;
this.suit = s;
}
//Mutators
//Make deck
public static void makeDeck(Card[] c, String[] r, String[] s) {
for (int i = 0; i < c.length; i++) {
c[i] = new Card(r[temp], s[temp2]);
temp++; temp2++;
//Reset rank and suit
if (temp > 12)
temp = 0;
if (temp2 > 3)
temp2 = 0;
}
deck = c;
}
//Accessors
//Return deck
public static Card[] getDeck() {
return deck;
}
//Shuffle
public static Card[] shuffle(Card[] c) {
for (int i = 0; i < c.length; i++) {
int rand = (int)(Math.random()*(i + 1));
//Don't let anything be in a slot that doesn't exist
while (rand > c.length) {
temp4 = (int)Math.random();
rand -= temp4;
}
if (rand < 0)
rand += temp4;
Card temp = c[i];
c[i] = c[rand];
c[rand] = temp;
}
deck = c;
return deck;
}
//Draw
public static Card draw(Card[] c) {
if (c != null) {
for (int i = 0; i < c.length; i++) {
if (c[i] != null) {
try {
return c[i];
} finally {
c[i] = null;} //Remove i from c
}
}
}
return null;
}
}
Player class:
import java.util.*;
public class Player {
private String name;
private Card[] hand = new Card[52];
private int handsize = 0;
//Constructor
public Player(String n) {
name = n;
}
//Mutators
public void addCard(Card c) {
hand[handsize] = c;
handsize++;
}
//Accessors
public String getName() {
return name;
}
public Card[] getHand() {
return hand;
}
}
Your draw method is broken.
// get the first non-null Card from the cards "c".
public static Card draw(Card[] c) {
if (c != null) {
for (int i = 0; i < c.length; i++) {
if (c[i] != null) {
try {
return c[i];
} finally {
// now remove element i from the `c` array.
c[i] = null;
}
}
}
}
return null;
}
The problem is with your loop
while (something.equals("yes"))
There's nothing that sets something to any other value, so this loop just goes around endlessly, until all the players have more than 52 cards. Once someone has more than 52 cards, adding a new card causes the exception.
I think you need to remove this while. The code inside it should only be run once.
I think the order of your code is incorrect (hard to tell with this code)
for (int i = 1; i < 8; i++)
{
one.addCard(Card.draw(deck));
deck = Card.getDeck();
two.addCard(Card.draw(deck));
deck = Card.getDeck();
}
maybe should be
for (int i = 1; i < 8; i++)
{
deck = Card.getDeck();
one.addCard(Card.draw(deck));
deck = Card.getDeck();
two.addCard(Card.draw(deck));
}
Update
Also
public void addCard(Card c) {
hand[handsize] = c;
handsize++;
}
handsize is never incremented - it is always 0

Deck of Cards issue -Java [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I am having problems getting this DeckOfCards class to compile. It keeps telling me that it cannot find the symbol when pointing to Deck2.Shuffle() and Deck2.deal(). Any ideas why?
import java.lang.Math;
import java.util.Random;
public class DeckOfCards {
private Cards[] Deck;
private int cardHold;
public DeckOfCards() {
Deck = new Cards[52];
int n = 0;
for (int i = 1; i <= 13; i++) {
for (int j = 1; j <= 4; j++) {
Deck[n] = new Cards(i, j);
n = n + 1;
}
}
cardHold = -1;
}
public void Shuffle() {
// shuffles ands resets deck
int i = 0;
while (i < 52) {
int rando = (int) (5.0 * (Math.random()));
Cards temp = Deck[rando];
Deck[rando] = Deck[i];
Deck[i] = temp;
i++;
}
}
public Cards deal() {
// if there are any more cards left in the deck, return the next one and
// increment
// index; return null if all the cards have been dealt
// ***Question, increment before or
// after??***----------------------------------------
if (!hasMoreCards()) {
return null;
} else {
Cards temp = null;
temp = Deck[cardHold];
cardHold = cardHold + 1;
return temp;
}
}
public boolean hasMoreCards() {
// returns true if there are more cards left, else return false
if (cardHold == 0)
return false;
else
return true;
}
public static void main(String[] args) {
DeckOfCards Deck2 = new DeckOfCards();
Deck2.Shuffle();
for (int i = 0; i < 52; i++)
System.out.println(Deck2.deal());
}
}
Below class is Card class, maybe that is causing the issue?
public class Cards {
protected int rank;
protected int suit;
protected String[] sNames = { "Hearts", "Clubs", "Spades", "Diamonds" };
protected String[] rNames = { "Ace", "2", "3", "4", "5", "6", "7", "8",
"9", "10", "Jack", "Queen", "King" };
public Cards(int Rank, int Suit) {
suit = Suit;
rank = Rank;
}
public String toString() {
return ("Your card is: " + rNames[rank - 1] + " of " + sNames[suit - 1]);
}
public int getRank() {
return rank;
}
public int getSuit() {
return suit;
}
}
Your compiler issues are behind you, but there are lots of issues with your code.
public class DeckOfCards {
private Cards[] deck;
private int cardHold;
public DeckOfCards() {
deck = new Cards[52];
int n = 0;
for (int i = 1; i <= 13; i++) {
for (int j = 1; j <= 4; j++) {
deck[n] = new Cards(i, j);
n = n+1;
}
}
cardHold = -1;
}
public void shuffle() {
int i = 0;
while (i < 52) {
int rando = (int) (5.0*(Math.random()));
Cards temp = deck[rando];
deck[rando] = deck[i];
deck[i] = temp;
i++;
}
}
public Cards deal() {
return (hasMoreCards() ? deck[++cardHold] : null);
}
public boolean hasMoreCards() {
return (cardHold != 0);
}
public static void main(String[] args) {
DeckOfCards deck2 = new DeckOfCards();
deck2.shuffle();
for (int i = 0; i < 52; i++)
System.out.println(deck2.deal());
}
}
And:
public class Cards {
protected int rank;
protected int suit;
protected String[] sNames = {"Hearts", "Clubs", "Spades", "Diamonds"};
protected String[] rNames = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
public Cards(int rank, int suit) {
this.suit = suit;
this.rank = rank;
}
public String toString() {
return ("Your card is: "+rNames[rank-1]+" of "+sNames[suit-1]);
}
public int getRank() {
return rank;
}
public int getSuit() {
return suit;
}
}
You are using an assignment operator in the if statement expression here:
if (cardHold = 0)
Replace with
if (cardHold == 0)
you may want to add import java.util.Date; and the shuffle function and call in the main is different one have 's'and the other 'S'.
Try this:
import java.lang.Math;
import java.util.Date;
import java.util.Random;
public class DeckOfCards {
private Cards[] Deck;
private int cardHold;
private Random rand;
public DeckOfCards() {
rand = new Random();
Date d = new Date();
rand.setSeed(d.getTime());
Deck = new Cards[52];
int n = 0;
for (int i = 1; i <= 13; i++) {
for (int j = 1; j <= 4; j++) {
Deck[n] = new Cards(i, j);
n = n + 1;
}
}
cardHold = 0;
}
public void shuffle() {
// shuffles ands resets deck
int i = 0;
while (i < 52) {
// int rando = (int)(5.0 * (Math.random()));
int rando = rand.nextInt(52);
Cards temp = Deck[rando];
Deck[rando] = Deck[i];
Deck[i] = temp;
i++;
}
}
public boolean hasMoreCards() {
// returns true if there are more cards left, else return false
if (cardHold == 0)
return false;
else
return true;
}
public static void main(String[] args) {
DeckOfCards Deck2 = new DeckOfCards();
Deck2.shuffle();
for (int i = 0; i < 52; i++)
System.out.println(Deck2.Deck[i]);
}
}

Categories

Resources