我在Java中使用Iterator编写了一个程序来编写堆栈。但我不明白为什么我会得到空指针异常。
这是我的堆栈类
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;
}}
我的主要课程是这个
import java.util.Scanner;
public class evaluate
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
String s=input.nextLine();
linkedStack1<String> ops = new linkedStack1<String>();
linkedStack1<Double> vals = new linkedStack1<Double>();
String op;
double a,b;
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)=='(');
else if(s.charAt(i)=='+' || s.charAt(i)=='*'
|| s.charAt(i)=='-' || s.charAt(i)=='/')
ops.push(Character.toString(s.charAt(i)));
else if(s.charAt(i)==')')
{
op =ops.pop();
a=vals.pop();
b= vals.pop(); // ERROR SHOWING HERE
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);
}
else if(s.charAt(i)==' ')
continue;
else
vals.push(Double.parseDouble(Character.toString(s.charAt(i)) ));
}
System.out.println(vals.pop());
}
}
但是当我为某些输入执行此代码时,请说(1+(2 * 3)), 我得到空指针异常
Exception in thread "main" java.lang.NullPointerException
at linkedStack1.pop(linkedStack1.java:47)
at evaluate.main(evaluate.java:25)
我已经在指定的行号前面做了评论,所以你可以看一下, 并帮我弄清楚代码中的错误是什么!!
答案 0 :(得分:1)
如果您的筹码为空并且您致电pop
,则first.item
会抛出NullPointerException
,因为first
为空。
这意味着你在这里弹出的元素多于堆栈中存在的元素:
a=vals.pop();
b= vals.pop(); // ERROR SHOWING HERE
你应该在调用pop之前检查堆栈是否为空。
答案 1 :(得分:1)
您的first
元素已初始化为null
。
私有节点first = null;
但是您在pop
之前运行的push()
方法中使用它,您可以在其中指定新值。您可以将first
初始化为有效值,或者将代码更改为在push()
之前使用pop()
。
答案 2 :(得分:1)
教科书错误。
您需要比较引用(==
)而非值(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);
另见: