I wrote a program to make a stack with the help of Iterator in Java. But I don't understand, why I am getting the NullPointerException.
Here is my class for stack:
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;
}}
And my main class is this:
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());
}
}
But when I execute this code for some input, say (1+(2*3)),
I get the NullPointerException:
Exception in thread "main" java.lang.NullPointerException at linkedStack1.pop(linkedStack1.java:47) at evaluate.main(evaluate.java:25)
I have made the comments in front of the specified line numbers, so you can have a look at that, and help me figuring out what's the bug in my code!
first.item. Ifitemwhere NULL you wouldn't get an error right? sofirstmust be NULL? What isfirstinitialized to and when is it set to another value? That will show you how/why it is still NULL now and then you can correct your code.