[英]Getting Null Pointer Exception with Java
我用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)
我已经在指定的行号前面添加了注释,因此您可以查看一下,并帮助我弄清楚代码中的错误!!
当堆栈为空并调用pop
,由于first
为null,因此first.item
会引发NullPointerException
。
这意味着您在这里弹出的元素多于堆栈中存在的元素:
a=vals.pop();
b= vals.pop(); // ERROR SHOWING HERE
您应该在调用pop之前检查堆栈是否为空。
您的first
元素被初始化为null
。
专用节点first = null;
但是,您可以在push()
之前运行的pop
方法中使用它,在其中分配新值。 您可以first
其初始化为有效值,或者将代码更改为在pop()
之前使用push()
pop()
。
教科书错误。
您正在比较引用( ==
)而不是值( 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);
也可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.