所以我有一个聊天室,它曾经可以工作,但我稍微改变了代码来尝试一些东西,但它们不起作用,所以我尝试恢复到原来的代码,但我不确定我要做什么做错了,因为现在它抛出 NullPointerException。我的代码有一个 PrintWriters 的 ArrayList 和一个方法 showAll() ,它的作用就像它所说的那样;向聊天室中的所有人发送消息。所以基本上我想知道我为什么会得到异常(exception)?
//This is the main code, used to add printwriters to the arraylist and to connect to clients
//The Communicate thread is used to get input from users and use the showAll() method with that input
public void listen() {
listWriters = new ArrayList<PrintWriter>();
try {
scanner = new Scanner(System.in);
portnum = getPortNumber(scanner);
System.out.println("Listening on " + portnum);
serverSocket = new ServerSocket(portnum);
while(true) {
clientcommunicate = serverSocket.accept();
System.out.println("Connection accepted: " + clientcommunicate.toString());
PrintWriter client = new PrintWriter(clientcommunicate.getOutputStream(), true);
listWriters.add(client);
Thread t = new Thread(new Communicate(clientcommunicate));
t.start();
}
} catch (IOException ioe) {
System.err.println(ioe);
System.err.println("Error.");
System.exit(1);
}
}
//This uses a printwriter obtained in the Communicate thread; the thread initializes a socket in it with the socket obtained in the constructor
public void showAll(String msg, PrintWriter printwriter) {
for(int i = 0; i < listWriters.size(); i++) { //this is where the exception is thrown
if(!listWriters.get(i).equals(printwriter)) { //if I change the paramater listWriters.size() to a regular integer like 3, and only create 2 clients or even less, the exception is thrown here instead
listWriters.get(i).println(msg);
}
}
}
编辑:
好的,我不再收到错误消息,但现在我似乎无法发送消息。如果我从客户端发送消息,则不会出现错误,但消息不会显示在任一客户端上。
最佳答案
由于您试图取消引用(即调用方法或从中读取字段)一个 null
变量,您将抛出一个 NullPointerException
。
在本例中,很明显 listWriters
为 null(因为它是在发生异常的行上唯一取消引用的变量 - 查找 .
字符) 。由于这是在您的 listen()
方法中分配的,因此我猜想,如果您在调用 showAll()
之前 调用 时,您会收到此错误>听()
。
一个非常简单的字段是在其声明中将 listWriters
分配给一个空列表,这样它就永远不会为空:
private List<PrintWriter> listWriters = new ArrayList<PrintWriter>();
根据应用程序的并发要求,您可能需要做一些更复杂的事情,但一般原则是您必须在尝试读取之前初始化listWriters
它。
关于java - 在 Java 中调用 ArrayList.get() 时出现 NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13010108/