在数组列表

时间:2016-04-16 19:34:24

标签: java arraylist nullpointerexception

我创建了一个简单的服务器和客户端应用程序,当服务器运行并且新客户端连接时,应该将新用户添加到" Bidder"应输出类及其名称,在这种情况下,我使用的名称是静态的,用户没有输入他们的名字,即#34; Jordan"在这种情况下。因此,在客户端连接时,添加新的投标人,然后检索并输出该投标人。但是在输出时我收到空指针异常。

检索用户名称:

final ArrayList<String> userNames = new ArrayList<String>();
    Bidder bidder1 = null;
    final Bidder bidder = new Bidder(timeNow, client, bidder1, PORT);
    final Users user = new Users(itemOne,itemTwo);
    final ArrayList<ClientHandler> users =
                            new ArrayList<ClientHandler>();

    do
    {
        client = serverSocket.accept();
        System.out.println("\nUser" + (user.getNumOfUsers()+1)
                                        + " has been accepted to the auction system.\n");
        System.out.println(bidder.getUserName());
        user.incUsers(users, client, handler);

    }while (true);

竞标者类:

class Bidder
{
    private ArrayList<Bidder> userNamesHandle;

    public Bidder(String name, Socket client, Bidder bidder, int i)
    {
        userNamesHandle = null;
    }
    public synchronized void createUser(ArrayList<Bidder> userList,final Socket
            client,Bidder handler)
    {
            String name = "Jordan";
            userList = userNamesHandle;
            int incrementUsers=0;

            for (final Bidder newBidder:userNamesHandle)
            {
                incrementUsers++;
            }
            userList.add(incrementUsers, handler = new Bidder(name, client, this, incrementUsers+1));
    }
    public synchronized Bidder getUserName()
    {
        int newNumOfUsers = 0;
        if(userNamesHandle != null)
        {
            for(final Bidder String:userNamesHandle)
            {
                newNumOfUsers++;
            }
        }
        return userNamesHandle.get(newNumOfUsers);
    }
}

我相信用户的名字正被添加到ArrayList中,但我无法检索它,我不确定为什么。

1 个答案:

答案 0 :(得分:0)

问题出在班级getUserName的{​​{1}}方法中。

如果Bidderreturn userNamesHandle.get(newNumOfUsers);,则NullPointerException语句会抛出userNamesHandle

在类的构造函数中,将其初始化为null