|
-
November 12th, 2009, 01:56 PM
#1
help - nullpointerexception error
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.
Code:
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));
}
}
-
November 12th, 2009, 02:11 PM
#2
Re: help - nullpointerexception error
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.
-
November 12th, 2009, 02:21 PM
#3
Re: help - nullpointerexception error
Thank you so much. Everything works now.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|