2011-10-30 25 views
-3

我實現了一些代碼,包括隊列,當運行它,我得到一個NullPointerException.Please幫我解決它。我現在只是編寫代碼的縮寫形式。的NullPointerException在隊列

import java.util.*; 
class ex 
{ 
public static void main(String args[])throws IOException 
{ 

    Scanner in=new Scanner(System.in); 
    int i; 
    String s; 
    int n=in.nextInt(); 

    Queue<Integer> q=null; 
    for(i=0;i<n;i++) 
    { 
     q.add(i);//I get the error in this line 
    } 
    System.out.println(q.size()); 
} 
} 

回答

2

你必須首先初始化隊列:

Queue<Integer> q=null; 

應該是:

Queue<Integer> q = new Queue<Integer>(); 

的原因錯誤是,你正試圖將值添加到q。 q被設置爲僅是類型Queue<Integer>的並且不被該類型本身的一個對象的引用。

1
Queue<Integer> q = null; 

嗯......這是null和:

q.add(i); 

有你想使用它。異常,異常。

你必須實例化爲了對象有一個,你可以使用:

Queue<Integer> q = new Queue<Integer>(); 

如果這不是一個簡單的錯字/監督,你可能想在的從頭開始通過Oracle或提供的Java教程解決更復雜的東西之前得到一個「學習Java」類型的書。

0

你得到的NPE因爲qnull

你必須創建一個對象,然後才能使用它,例如:

Queue<Integer> q = new LinkedList<Integer>(); 

在這裏,我挑選LinkedList作爲實施Queue接口的類。有很多其他的:看到Queue javadoc的「所有已知實現類」部分。

0
Queue<Integer> q=null; 
... 
q.add(i);//I get the error in this line 

Queue引用null,所以試圖訪問它時,你會得到一個NullPointerException。之前使用它,q必須指向有效的東西一樣,例如:

Queue<Integer> q = new Queue<Integer>();