使用Java获取空指针异常
我在Java的迭代器帮助下编写了一个程序来生成堆栈。但我不明白为什么会出现空指针异常 这是我的stack课程使用Java获取空指针异常,java,nullpointerexception,Java,Nullpointerexception,我在Java的迭代器帮助下编写了一个程序来生成堆栈。但我不明白为什么会出现空指针异常 这是我的stack课程 import java.util.Iterator; public class linkedStack1<Item> implements Iterable<Item> { public Iterator<Item> iterator() { return new listIterator(); } private class lis
import java.util.Iterator;
public class linkedStack1<Item> implements Iterable<Item>
{
public Iterator<Item> iterator()
{
return new listIterator();
}
private class listIterator implements Iterator<Item>
{
private node current = first;
public boolean hasNext() { return current!=null;}
public Item next()
{
Item item = current.item;
current=current.next;
return item;
}
}
private node first=null;
private class node
{
Item item;
node next;
}
public boolean isEmpty()
{
return first==null;
}
public void push(Item item)
{
node oldFirst=first;
first=new node();
first.item=item;
first.next=oldFirst;
}
public Item pop()
{
Item item=first.item; // ERROR SHOWING HERE
first=first.next;
return item;
}}
我已经在指定的行号前面做了评论,所以你可以看一下,
帮我找出代码中的错误 当堆栈为空且调用
pop
时,首先调用。项
抛出一个NullPointerException
,因为first
为空
这意味着您在此处弹出的元素比堆栈中存在的元素多:
a=vals.pop();
b= vals.pop(); // ERROR SHOWING HERE
在调用pop之前,应该检查堆栈是否为空。您的
第一个元素已初始化为null
private node first=null
但是在push()
之前运行的pop
方法中使用它,在该方法中指定一个新值。您可以先将初始化为有效值,或者在pop()
出现教科书错误之前,将代码更改为使用push()
您正在比较引用(==
)而不是值(equals()
)。
操作的结果不是被推到堆栈上
试试这个:
if(op.equals("+")) vals.push(b+a);
else if(op.equals("-")) vals.push(b-a);
else if(op.equals("*")) vals.push(b*a);
else if(op.equals("/")) vals.push(b/a);
代替:
if(op=="+") vals.push(b+a);
else if(op=="-") vals.push(b-a);
else if(op=="*") vals.push(b*a);
else if(op=="/") vals.push(b/a);
另见:
的可能重复,因此错误显示first.item中有空指针。如果item
where NULL,您不会得到正确的错误吗?那么first
必须为空?首先初始化为什么,何时设置为另一个值?这将向您展示它现在仍然为NULL的方式/原因,然后您可以更正代码。但这并不意味着从堆栈中弹出元素会改变任何东西。@RomanC当堆栈为空时,first
为NULL,pop()抛出NullPointerException
。无论你在调用push之前是否调用pop,或者调用push 4次,然后调用pop 5次,都没有关系。结果是一样的。
if(op.equals("+")) vals.push(b+a);
else if(op.equals("-")) vals.push(b-a);
else if(op.equals("*")) vals.push(b*a);
else if(op.equals("/")) vals.push(b/a);
if(op=="+") vals.push(b+a);
else if(op=="-") vals.push(b-a);
else if(op=="*") vals.push(b*a);
else if(op=="/") vals.push(b/a);