1

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!

2
  • 2
    possible duplicate of What is a Null Pointer Exception, and how do I fix it? Commented Mar 9, 2015 at 13:34
  • So the error says that there is a null pointer in first.item. If item where NULL you wouldn't get an error right? so first must be NULL? What is first initialized 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. Commented Mar 9, 2015 at 13:49

3 Answers 3

1

When your stack is empty and you call pop, first.item throws a NullPointerException since first is null.

This means you are popping more elements than exist in your stack here :

        a=vals.pop();
        b= vals.pop();            // ERROR SHOWING HERE

you should check the stack is not empty before calling pop.

Sign up to request clarification or add additional context in comments.

2 Comments

But it doesn't mean that popping elements from the stack would change anything.
@RomanC when the stack is empty, first is null, and pop() throws NullPointerException. It doesn't matter if you call pop before ever calling push, or call push 4 times and then pop 5 times. The result would be the same.
1

Your first element is initialized to null.

private node first=null;

But you use it in the pop method running before push() where you assign a new value. Either you initialize first to a valid value or change your code to use push() before the pop().

Comments

1

A textbook error.

You're comparing references (==) not values (equals()). The result of the operation is not getting pushed onto the stack

Try this:

        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);

In place of:

        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);

See also:

How do I compare strings in Java?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.