所以我有一個聊天室,它曾經工作,但我稍微改變了代碼來嘗試一些事情,他們沒有工作,所以我試圖恢復到我原來的代碼,但我不知道我做了什麼因爲現在它拋出了NullPointerException。我的代碼有一個PrintWriters的ArrayList和一個方法showAll(),它的確如它所說;發送消息給聊天室中的所有人。所以基本上我想知道的是我如何得到這個異常?在Java中調用ArrayList.get()時獲取NullPointerException?
//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);
}
}
}
編輯:
好了,所以我不再得到的錯誤,但現在我似乎無法發送消息。如果我從客戶端發送消息,則沒有錯誤,但消息不會在任何客戶端上顯示。
或者'listen()'和'showAll()'在不同的對象上被調用。 – axtavt
@axtavt這是一個好點和一個bug的潛在原因(儘管只是一個改進,因爲問題仍然是showAll對象沒有調用listen()。 –
擺脫了NullPointerException,感謝那,但現在我仍然無法設法得到消息發送,即使沒有錯誤。任何想法爲什麼? –