2

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 null pointer exception.

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 null pointer exception

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!!

Razib
  • 10,965
  • 11
  • 53
  • 80
thisisashwani
  • 1,748
  • 2
  • 18
  • 25
  • 2
    possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Jens Mar 09 '15 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. – verdammelt Mar 09 '15 at 13:49

3 Answers3

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • But it doesn't mean that popping elements from the stack would change anything. – Roman C Mar 09 '15 at 13:50
  • @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. – Eran Mar 09 '15 at 13:53
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().

Roman C
  • 49,761
  • 33
  • 66
  • 176
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?

Community
  • 1
  • 1
Persixty
  • 8,165
  • 2
  • 13
  • 35