简体   繁体   中英

Getting Null Pointer Exception with Java

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

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.

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() .

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM