2011-10-30 23 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>();