Click to See Complete Forum and Search --> : help - nullpointerexception error


Flakk
November 12th, 2009, 12:56 PM
This code is supposed to perform postfix calculations. Everything compiles fine. However, every time I run the code, I run into this error:

java.lang.NullPointerException
at postfixCalculator.calculate(postfixCalculator.java:77)
at postfixCalculator.main(postfixCalculator.java:90)

Any kind of help would be great.


import java.io.*;
import java.util.Scanner;
import java.util.Stack;

public class postfixCalculator{

Stack<String> calculator;

public postfixCalculator(){

calculator = null;

}

public String add(){
Integer a = Integer.valueOf(calculator.pop());
Integer b = Integer.valueOf(calculator.pop());
Integer c = a+b;
return c.toString();
}

public String subtract(){
Integer a = Integer.valueOf(calculator.pop());
Integer b = Integer.valueOf(calculator.pop());
Integer c = b-a;
return c.toString();
}

public String multiply(){
Integer a = Integer.valueOf(calculator.pop());
Integer b = Integer.valueOf(calculator.pop());
Integer c = a*b;
return c.toString();
}

public String divide(){
Integer a = Integer.valueOf(calculator.pop());
Integer b = Integer.valueOf(calculator.pop());
Integer c = b/a;
return c.toString();
}

public String calculate(String exp){
String result;
String[] parse = exp.split(" "); // split the string, we need separate characters in exp

for (int i=0; i<parse.length; i++){
if (parse[i].equals("+"))
calculator.push(add());
else if (parse[i].equals("-"))
calculator.push(subtract());
else if (parse[i].equals("*"))
calculator.push(multiply());
else if (parse[i].equals("/"))
calculator.push(divide());
else
calculator.push(parse[i]);
}
result = calculator.pop();
if (!calculator.empty()){
System.out.println("Error");
System.exit(0);
}
return result;
}
public static void main(String args[]) {
postfixCalculator pc = new postfixCalculator();
Scanner sc = new Scanner(System.in);
String expression = sc.nextLine();
System.out.println("Expression evaluates to " + pc.calculate(expression));
}
}

themoffster
November 12th, 2009, 01:11 PM
you are telling the calculator to push/pop an item in the calculate method, but the calculator is instantiated to null in the constructor and it isn't set to be anything else elsewhere.

you need to set the calculator variable to be a new stack/whatever.

Flakk
November 12th, 2009, 01:21 PM
Thank you so much. Everything works now.