开发者

Case specific null pointer exception problem - java [duplicate]

This question already has answers here: What is a NullPointerException, and how do I fix it? (12 answers) Closed 5 years ago.

I have a strange pro开发者_开发百科blem regarding null pointer exception. I'm posting the problematic code piece below :

public static void main(String[] args) {

BetHistory testObject = new BetHistory(6);

testObject.addResponse(2, 1, 0); //  ERROR HERE

...

}

public class PlayerResponses {

    public List<Integer> response;

    public PlayerResponses() {
        super();
        response = new LinkedList<Integer>();
    }

...

}

public class BetHistory {

    PlayerResponses [][] responses; 
    int nPlayer;

    public BetHistory(int totalPlayers) {
        super();
        responses = new PlayerResponses[4][totalPlayers];
        nPlayer = totalPlayers;

        }
    public void addResponse(int response, int playerNo, int roundNo)
    {
        responses[roundNo][playerNo].response.add(response); // DUE TO HERE
    }

...

}

Thanks in advance for your time.


In this line:

responses = new PlayerResponses[4][totalPlayers];

You create a 2-dimensional array that can hold references to PlayerResponses objects. You don't create even a single PlayerResponses object.

You need to fill in those in a loop (or later on on-demand, if you want):

responses[i][j] = new PlayerResponses();


That's because public List<Integer> response; in each of the PlayerResponses stored in the array are not initialized. It gets the default null, that's why when you call the add method you get the NPE.


import java.util.*;

    public class A {
    public static void main(String[] args) {

            BetHistory testObject = new BetHistory(6);

            testObject.addResponse(2, 1, 0); //  ERROR HERE

    }
    }

    class PlayerResponses {

        public LinkedList<Integer> response;

        public PlayerResponses() {
            super();
            response = new LinkedList<Integer>();
        }


    }

    class BetHistory {

        PlayerResponses [][] responses; 
        int nPlayer;

        public BetHistory(int totalPlayers) {
            super();
            responses = new PlayerResponses[4][totalPlayers];
            for(int i=0;i<totalPlayers;i++) {
                            responses[0][i] = new PlayerResponses();
                            responses[1][i] = new PlayerResponses();
                            responses[2][i] = new PlayerResponses();
                            responses[3][i] = new PlayerResponses();
                    }
            nPlayer = totalPlayers;

            }
        public void addResponse(int response, int playerNo, int roundNo)
        {
            responses[roundNo][playerNo].response.add(response); // DUE TO HERE
        }


    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜