2012-10-22 48 views
0

所以我有一個聊天室,它曾經工作,但我稍微改變了代碼來嘗試一些事情,他們沒有工作,所以我試圖恢復到我原來的代碼,但我不知道我做了什麼因爲現在它拋出了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); 
      } 
     } 
    } 

編輯:

好了,所以我不再得到的錯誤,但現在我似乎無法發送消息。如果我從客戶端發送消息,則沒有錯誤,但消息不會在任何客戶端上顯示。

回答

6

由於您試圖對null的變量進行解引用(即調用方法或從中讀取字段),因此拋出了NullPointerException

在這種情況下,很明顯,listWriters是空的(因爲它是對將發生異常行取消引用的唯一變量 - 尋找.字符)。由於這被分配在您的listen()方法中,所以我想如果您在之前調用showAll(),則會調用listen()來得到此錯誤。

一個非常簡單的領域將分配listWriters空列表在其聲明中,使得它不能爲null:

private List<PrintWriter> listWriters = new ArrayList<PrintWriter>(); 

根據應用程序的併發需求,你可能需要做一些事情更詳細一點,雖然一般原則是你必須在之前初始化listWriters你嘗試從它讀取。

+1

或者'listen()'和'showAll()'在不同的對象上被調用。 – axtavt

+0

@axtavt這是一個好點和一個bug的潛在原因(儘管只是一個改進,因爲問題仍然是showAll對象沒有調用listen()。 –

+0

擺脫了NullPointerException,感謝那,但現在我仍然無法設法得到消息發送,即使沒有錯誤。任何想法爲什麼? –

0

您必須在listen方法之前調用showAll方法。 在您的showAll方法之前,您的ListWriters未在listen方法中初始化。

0

這可能是因爲你已經初始化了listWriters裏面的listen()方法。

因此,如果您showAll()方法被前listen()方法調用,它將得到您的listWriters一個null值(假設你已經宣佈listWriters作爲實例變量,並沒有初始化,有本身)。

您可以在您聲明它的地方嘗試initializing

private List<PrintWriter> listWriters = new ArrayList<PrintWriter>(); 
相關問題