0

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;   
    }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
William
  • 23
  • 1
  • 5

3 Answers3

1

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;
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • In what way is the original `draw` method broken? It looks fine to me, other than the fact that it creates lots of duplicates of the last card in the deck (which wouldn't give an ArrayIndexOutOfBoundsException). – Dawood ibn Kareem Dec 18 '13 at 01:47
  • @DavidWallace you don't see a problem with the line `c = deck;`? – Elliott Frisch Dec 18 '13 at 01:48
  • just put that in and I have the same error in teh same spot. it occurs at the line in my player class where hand[handsize] = c; the other part occuurs at the line where I one.addCard(...); – William Dec 18 '13 at 01:50
  • @ElliottFrisch, deck and c are both Card[] (Card object arrays) – William Dec 18 '13 at 01:51
  • @William I'm aware of that. – Elliott Frisch Dec 18 '13 at 01:53
  • @ElliottFrisch, i just added all of my code to this question post – William Dec 18 '13 at 02:05
  • @William your code is broken in several ways...Make a deck, shuffle a deck, and take out the lines `deck = Card.getDeck();` – Elliott Frisch Dec 18 '13 at 02:08
  • @ElliottFrisch, no, I don't see a problem with that line, that would prevent the code from working. While this method is running, `c` is already equal to `deck` so that line will do nothing. – Dawood ibn Kareem Dec 18 '13 at 02:17
0

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

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

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.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
  • thanks. i will get rid of it to see if this fixes my problem, but i will need it to be able to replay my game. – William Dec 18 '13 at 12:24
  • i just realized that some of my code was missing when i ran it for some reason.. i added it back, and i still get the same error... it isnt the while loop. – William Dec 18 '13 at 12:41
  • what you mean , it is not while loop. @David provided clear explanation and that is cauing issue. If you want to Replay your Game you have to reset the cards in Player's Hand ( i.e Reset the handsize to 0 for every while loop ( if you think player should have only 8 cards at given time) – Mani Dec 18 '13 at 13:59
  • So you're saying that your program is actually something different from what's posted above? In the program that you posted above, the problem is the while loop, and the fact that it repeats endlessly without setting the players' hands back to empty. If you're actually running a different program from what you've posted, then none of us can help you. – Dawood ibn Kareem Dec 18 '13 at 20:20
  • @DavidWallace, you were actually a big help. I found a different error thanks to you (that is now fixed). I am one error away from finished and i just posted a question for it. – William Dec 19 '13 at 02:20
  • OK. I seriously recommend that once you have this working, you post it on codereview.stackexchange.com. There are many things about your program that are not quite errors, but are really not very good. The people who hang out on that site will take great delight in listing them for you. – Dawood ibn Kareem Dec 19 '13 at 05:44