Java Array Index Out of Bounds somehow?

前端 未结 3 743
隐瞒了意图╮
隐瞒了意图╮ 2020-12-22 08:49

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

相关标签:
3条回答
  • 2020-12-22 09:24

    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;
    }
    
    0 讨论(0)
  • 2020-12-22 09:25

    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

    0 讨论(0)
  • 2020-12-22 09:36

    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.

    0 讨论(0)
提交回复
热议问题