проблема кодирования Java: зависает на добавлении arraylist - PullRequest
0 голосов
/ 06 февраля 2011

Я использовал ранее arraylist как структуру, но в этом фрагменте кода это не работает.Может ли кто-нибудь помочь мне, так как я не могу найти ошибку?(я уверен, что это моя ошибка, но IDE ничего не говорит)

поток: сначала классная игра.я вызываю runGame и он течет нормально, пока точка Hand hand = new Hand (this.deck); (там есть комментарий о праве обозначить проблему

public class Game {

        private ArrayList<Player> playerArray;
    private int maxPlayers;
        private Deck deck;

    //constructor
    public Game(ArrayList playerArray, int maxPlayers)
    {
        this.playerArray = playerArray;
        this.maxPlayers = maxPlayers;
        }

    // game method for the match
    public  void runGame()
        {
            //shuffle of players
            Collections.shuffle(this.playerArray);

            //creation of the deck
            this.deck = new Deck();
            System.out.println(new java.util.Date().toString() +"  "+"deck created");

            //shuffle the deck 
            this.deck.shuffleDeck();
            System.out.println(new java.util.Date().toString() +"  "+"deck shuffled");


            // distribuiting the hands to all players
            //and preventing them to send something
            for (int i = 0; i < this.maxPlayers; i++)
            {
                Player currentPlayer = this.playerArray.get(i);
                Socket socket = currentPlayer.getConnection();

                Hand hand = new Hand(this.deck);// the problem starts here  comes form the constructor of the hand
                 System.out.println(" after hand ");

                sendingBlockString(socket, currentPlayer); //send the block string
                sendingHand(socket, currentPlayer, hand );//send the hand
            }

проблема явно заключается в конструкторе hand в классе Hand, где он зависает в цикле, exaclty пытается добавить вытолкнутый вагон колоды (функция deck.popCard () протестирована и работает отлично, поэтому блокировка добавления не такова() функция) я никогда не получаю второй system.out.println здесь код:

public class Hand  implements Serializable
{

    private ArrayList<Card> theHand;
    private Player player;
    private int handValue ;  // from 1  to 10 


        public Hand(Deck deck)
        {
            for (int i=0; i<4; i++)
            { 
                System.out.println("before popping deck");
                this.theHand.add(i, deck.popCard());// adding the card taken from the deck (5 times)  //// this is the problem  it hangs!
                System.out.println("after add to hand");
            }

         }

Ответы [ 2 ]

1 голос
/ 06 февраля 2011

Я подозреваю, что dec.popCard() блокируется, если больше нет карт.сам метод add не может зависнуть.

1 голос
/ 06 февраля 2011

Вы уверены, что он зависает? Он должен выдавать исключение NullPointerException, поскольку ваш ArrayList не инициализирован.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...