【问题标题】:Java Array Index Out of Bounds somehow?Java数组索引以某种方式越界?
【发布时间】:2014-01-06 01:01:20
【问题描述】:

在我的游戏代码中,我正在尝试添加一张牌。一旦我这样做,我的数组就超出了界限。一切看起来都不错,但也许我遗漏了什么。

仅供参考,一和二是 Player 实例。 Main 类的相关代码(对格式感到抱歉。我很讨厌将其转移到 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();
                }
            }
        }
    }
}

卡类:

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

播放器类:

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

【问题讨论】:

  • 与您的错误无关,但这些 Player 方法/变量都不应该是静态的。
  • 我认为您的错误不在您发布的代码中。你能展示你的整个节目吗?
  • @DavidWallace,我刚刚将我所有的代码添加到这个问题帖子中
  • 你遇到了什么错误,在哪一行?

标签: java arrays exception indexing poker


【解决方案1】:

你的draw方法坏了。

// 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;
}

【讨论】:

  • 原来的draw方法是怎么破的?对我来说它看起来不错,除了它会在牌组中创建许多最后一张牌的副本(不会给出 ArrayIndexOutOfBoundsException)。
  • @DavidWallace 你看不出c = deck;这行有问题吗?
  • 只要把它放进去,我在同一个地方也有同样的错误。它发生在我的播放器类中 hand[handsize] = c; 的行另一部分发生在我 one.addCard(...);
  • @ElliottFrisch,deck 和 c 都是 Card[](卡片对象数组)
  • @William 我知道。
【解决方案2】:

问题在于你的循环

while (something.equals("yes"))

没有任何东西可以将something 设置为任何其他值,所以这个循环会无限循环,直到所有玩家拥有超过 52 张牌。一旦某人拥有超过 52 张卡片,添加新卡片就会导致异常。

我认为您需要删除此while。里面的代码应该只运行一次。

【讨论】:

  • 谢谢。我会摆脱它,看看这是否能解决我的问题,但我需要它才能重玩我的游戏。
  • 我刚刚意识到,当我出于某种原因运行它时,我的一些代码丢失了。我把它加回去了,但我仍然得到同样的错误......这不是 while 循环。跨度>
  • 你的意思,不是while循环。 @David 提供了明确的解释,这就是问题所在。如果你想重玩你的游戏,你必须重置玩家手中的牌(即在每个 while 循环中将手的大小重置为 0(如果你认为玩家在给定时间应该只有 8 张牌)
  • 所以您是说您的程序实际上与上面发布的不同?在您在上面发布的程序中,问题在于 while 循环,事实上它会无限重复,而不会让玩家的手变空。如果您实际上运行的程序与您发布的程序不同,那么我们都无法帮助您。
  • @DavidWallace,你实际上帮了大忙。感谢您,我发现了一个不同的错误(现在已修复)。我距离完成还有一个错误,我刚刚发布了一个问题。
【解决方案3】:

我认为您的代码顺序不正确(用这段代码很难分辨)

for (int i = 1; i < 8; i++)
{
 one.addCard(Card.draw(deck));
 deck = Card.getDeck();
 two.addCard(Card.draw(deck));
 deck = Card.getDeck();
}

也许应该是

for (int i = 1; i < 8; i++)
{
 deck = Card.getDeck();
 one.addCard(Card.draw(deck));
 deck = Card.getDeck();
 two.addCard(Card.draw(deck));
}

更新

还有

public void addCard(Card c) {
    hand[handsize] = c;
    handsize++;
}

handsize 永远不会递增 - 它始终为 0

【讨论】:

  • 我有一张牌 = Card.getDeck();但它没有显示。我的整个代码在compilr.com/bottomsniffer/final/Program.java
  • 抱歉,我不想在其他网站注册,以便在这里回答您的问题。为什么不发布相关代码。
  • 我现在就全部贴出来
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-15
  • 2015-10-26
相关资源
最近更新 更多