I am trying to create a program which evaluates postfix expression.For example "3500 43 12 * 47 2 / + -" .Here is my code
public static int EvaluatePostfixExpression(String postfixExpr){
Stack s = new Stack();
int result = 0;
String operand = null;
for(int i = 0; i<postfixExpr.length();i++){
if(Character.isDigit(postfixExpr.charAt(i)) == true){
operand = operand + postfixExpr.charAt(i);
if(Character.isDigit(postfixExpr.charAt(i+1)) == false){
s.push(operand);
operand = null;
}
}
if(postfixExpr.charAt(i) == '+'){
result = result + Integer.parseInt((String) s.pop()) + Integer.parseInt((String) s.pop()) ;
}
if(postfixExpr.charAt(i) == '-'){
result = result + Integer.parseInt((String) s.pop()) - Integer.parseInt((String) s.pop()) ;
}
if(postfixExpr.charAt(i) == '*'){
result = result + Integer.parseInt((String) s.pop()) * Integer.parseInt((String) s.pop()) ;
}
if(postfixExpr.charAt(i) == '/'){
result = result + Integer.parseInt((String) s.pop()) / Integer.parseInt((String) s.pop()) ;
}
}
return result;
} //end-EvaluatePostfixExpression
When I try to run it, there occurs an error.
Exception in thread "main" java.lang.NumberFormatException: For input string: "null12"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
I can't find a solution.It would be great if anyone could help.
Edit: I handled the errors and my code now works;
public static int EvaluatePostfixExpression(String postfixExpr){
Stack s = new Stack();
int result = 0;
String operand = "";
for(int i = 0; i<postfixExpr.length();i++){
if(Character.isDigit(postfixExpr.charAt(i)) == true){
operand = operand + postfixExpr.charAt(i);
if(Character.isDigit(postfixExpr.charAt(i+1)) == false){
s.push(operand);
operand = "";
}
}
if(postfixExpr.charAt(i) == '+'){
int x = Integer.parseInt((String) s.pop()) + Integer.parseInt((String) s.pop());
result = result + x ;
s.push(String.valueOf(x));
}
if(postfixExpr.charAt(i) == '-'){
int x = Integer.parseInt((String) s.pop()) - Integer.parseInt((String) s.pop());
result = result + x ;
s.push(String.valueOf(x));
}
if(postfixExpr.charAt(i) == '*'){
int x = Integer.parseInt("" + s.pop()) * Integer.parseInt("" + s.pop());
result = result + x ;
s.push(String.valueOf(x));
}
if(postfixExpr.charAt(i) == '/'){
int x = Integer.parseInt((String) s.pop()) / Integer.parseInt((String) s.pop());
result = result + x ;
s.push(String.valueOf(x));
}
}
return result;
}
but now the result is wrong.It should be 2961 but I am getting -1952.
Try this one:
String operand = "";
Change it also when
if(Character.isDigit(postfixExpr.charAt(i+1)) == false){
s.push(operand);
operand = "";
}