Trying to Debug very glitchy blackjack game in java - 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!

Related

Arraylist IndexOutOfBoundsException? Need some help on this

I keep getting an IndexOutOfBoundsException when I run my code. I am using an ArrayList so I'm not sure why this is happening.
My ArrayList is
ArrayList<Card> cards = new ArrayList<Card>();
This is where the error occurs
public static void printCard(){
System.out.printf("%-20s %-20s\n", player1.name, player2.name);
for(int i = 0; i < 24; i++){
System.out.printf("%-20s %-20s\n", player1.getCard(i), player2.getCard(i));
} System.out.println();
}
Player class
public class Player {
public Deck mainDeck;
public Deck sideDeck;
public String name;
public int duelsWon;
public int totalCompares;
public Player(String name){
this.name=name;
mainDeck = new Deck();
sideDeck = new Deck();
duelsWon = 0;
totalCompares = 0;
}
public void addCard(Card newCard){
sideDeck.addCard(newCard);
}
public Card drawCard() throws OutOfCardsException{
if(mainDeck.numCards() == 0) {
addSideDeck();
}
if(mainDeck.numCards() == 0){
throw new OutOfCardsException();
}
Card c = mainDeck.drawCard();
return c;
}
public Card getCard(int i){
return mainDeck.cards.get(i);
}
/*public Card getCard(int i){
if(i < mainDeck.cards.size()) {
return mainDeck.cards.get(i);
}else{
}
return null;
}*/
public void addSideDeck(){
sideDeck.shuffle();
System.out.println("sideDeck: " + sideDeck.numCards());
for(int i = 0; i < sideDeck.numCards(); i++){
Card c = sideDeck.drawCard();
mainDeck.addCard(c);
}
}
}
Deck class
import java.util.ArrayList;
import java.util.Random;
public class Deck {
ArrayList<Card> cards = new ArrayList<Card>();
public Deck() {
}
public void addCard(Card c){
cards.add(c);
}
public Card drawCard(){
Card c = cards.remove(cards.size() - 1);
return c;
}
public Card getCard(){
return cards.get(cards.size() - 1);
}
public int numCards(){
return cards.size();
}
public void shuffle()
{
int index;
Card temp;
Random random = new Random();
for (int i = cards.size() - 1; i > 0; i--)
{
index = random.nextInt(i + 1);
temp = cards.get(index);
cards.set(index, cards.get(i));
cards.set(i, temp);
}
}
}
The answer is that you don't have 24 cards in your deck for one of your players. Nothing else will cause this with this code.
What is 24 ?
i think you need to check card size.
public static void printCard(){
System.out.printf("%-20s %-20s\n", player1.name, player2.name);
for(int i = 0; i < cards.size(); i++){
System.out.printf("%-20s %-20s\n", player1.getCard(i), player2.getCard(i));
} System.out.println();
}
I hope it help.
IndexOutOfBoundsException happens when you are trying to access an item which index is beyond the items stored in the ArrayList. Ex, if an ArrayList contains 5 items (index from 0 to 4) then if you try to access the ArrayList with index 5 then IndexOutOfBoundsException would be thrown.
Best approach to iterate though ArrayList/List are like:
for (Card c: cards) {
}
Or looping to the size
for (int i=0; i<cards.size(); i++) {
}
I think there is some issue with Random number you are getting
index = random.nextInt(i + 1);
temp = cards.get(index);
Just log the index and check if it is between 0 to cards.size();

I can not seem to create any of my objects in my main?

The point of the program is to display a poker and bridge hand. Those far when I run the program I can get it to display the poker description and then if exits. I would like it to continue and display the a poker hand then the bridge description and a bridge hand. I feel like my issues are coming from the abstract DeckOfCards class but Im really not sure.
I put all the classes in the same file to make it easier to follow and edit while programming.
When the program fails it gives these errors
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 52
at DeckOfCards.creatCardDeck(PlayCardGames.java:106)
at DeckOfCards.DeckOfCards(PlayCardGames.java:95)
at PlayCardGames.main(PlayCardGames.java:14)
Here is the program code it self (Thank you for editing it to format better)
import javax.swing.*;
import java.util.Random;
public class PlayCardGames {
public static void main(String[] args) {
Poker playPoker = new Poker();
playPoker.DeckOfCards();
playPoker.displayDescription();
playPoker.deal();
Bridge playBridge = new Bridge();
playBridge.DeckOfCards();
playBridge.displayDescription();
playBridge.deal();
}
}
//--------------------------------------------------------------------------------\\
interface DeckConstants{
final static int CARDS_IN_SUIT = 13;
final static int SUITS_IN_DECK = 4;
final static int CARDS_IN_DECK = CARDS_IN_SUIT * SUITS_IN_DECK;
}
//================================================================================\\
class Card{
private String suit;
private String rank;
private int rankIndex;
public Card(int suitIndex, int rankIndex){
setSuit(suitIndex);
setRank(rankIndex);
}
public String getSuit() {
if (suit.equalsIgnoreCase("Hearts")){ suit = "\u2665";}
else if (suit.equalsIgnoreCase("Diamonds")) { suit = "\u2666"; }
else if (suit.equalsIgnoreCase("Clubs")) { suit = "\u2663"; }
else if(suit.equalsIgnoreCase("Spades")) { suit = "\u2660"; }
return suit;
}
public void setSuit(int suitIndex) {
if (suitIndex == 1) {suit = "Spades";}
else if (suitIndex == 2) {suit = "Hearts";}
else if (suitIndex == 3) {suit = "Diamonds";}
else if(suitIndex == 4) {suit = "Clubs";}
}
public String getRank() {
if (rankIndex == 1) {rank = "Ace";}
else if (rankIndex == 11) {rank = "Jack";}
else if (rankIndex == 12) {rank = "Queen";}
else if(rankIndex == 13) {rank = "King";}
return rank;
}
public void setRank(int rankIndex) {
if (this.rankIndex >= 13){
this.rankIndex = 13;}
else if(this.rankIndex <= 1) {
this.rankIndex = 1;}
}
public String toString(String rank, String suit) {
return getRank() +" of " + getSuit();
}
}
//=================================================================================\\
abstract class DeckOfCards implements DeckConstants{
protected Card[] deck = new Card[CARDS_IN_DECK];
public void DeckOfCards(){
creatCardDeck();
shuffle(deck);
}
public void creatCardDeck() {
int numberOfCards = 0;
for (int suitCounter = 1; suitCounter < CARDS_IN_SUIT; suitCounter++)
{
for (int rankCounter = 1; rankCounter < CARDS_IN_SUIT; rankCounter++)
{
deck[numberOfCards] = new Card(suitCounter, rankCounter);
numberOfCards++;
}
}
}
public void shuffle(Card[] temp){
Random rnd = new Random();
for (int k = temp.length; k > 1; k--){
int i = k - 1;
int j = rnd.nextInt(k);
Card tmp = temp[i];
temp[i] = temp[j];
temp[j]= tmp;
}
}
public abstract void displayDescription();
public abstract void deal();
}
//===============================================================================\\
class Poker extends DeckOfCards{
private int cardsDealt = 5;
private int index = 0;
public void Poker(){
displayDescription();
deal();
}
public void displayDescription(){
String desc = "In poker, players bet on hands" +
"\n Winner can bluff or must have the highest hand if called";
JOptionPane.showMessageDialog(null, desc);
}
public void deal() {
String message = "Your Poker hand:\n";
for (int x = index; x < cardsDealt; x++){
message += deck[index] + "\n";
index++;
}
if (index == CARDS_IN_DECK){
shuffle(deck);
index = 0;
}
JOptionPane.showMessageDialog(null, message);
}
}
//===============================================================================\\
class Bridge extends DeckOfCards{
private int cardsDealt = 13;
private int index = 0;
public void Bridge(){
displayDescription();
deal();
}
public void displayDescription(){
String desc = "In bride, partners bid on how many tricks they will take." +
"\n The high bid determines a trump suit";
JOptionPane.showMessageDialog(null, desc);
}
public void deal() {
String message = "Your Bridge hand:\n";
for (int x = index; x < cardsDealt; x++){
message += deck[index] + "\n";
index++;
}
if (index == CARDS_IN_DECK){
shuffle(deck);
index = 0;
}
JOptionPane.showMessageDialog(null, message);
}
}
You know what, I think it is really simple:
Here is your code:
for (int suitCounter = 1; suitCounter < CARDS_IN_SUIT; suitCounter++)
{
for (int rankCounter = 1; rankCounter < CARDS_IN_SUIT; rankCounter++)
{
I think just maybe it should be:
for (int suitCounter = 1; suitCounter < SUITS_IN_DECK; suitCounter++)
{
for (int rankCounter = 1; rankCounter < CARDS_IN_SUIT; rankCounter++)
{

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]);
}
}

I need help drawing a Hand of Cards

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.

Categories

Resources