The code posted works for operations but wont work if there isnt spacing between the operators and operands.
I was given 4 expressions to compute
10 2 8 * + 3 -
3 14+2*7/
4 2 + 3 15 1 - * +
1 2 + 3 % 6 - 2 3 + /
(spacing is important)
Expression two is the one that will not compute using my current calculator
Here is my code
import java.util.*;
public class PostFix {
public static void main(String []args){
Stack<Integer> stack = new Stack<Integer>();
System.out.println("Input your expression using postfix notation");
Scanner input = new Scanner(System.in);
String expr = input.nextLine();
StringTokenizer tokenizer = new StringTokenizer(expr);
while(tokenizer.hasMoreTokens()){
String c = tokenizer.nextToken();
if(c.startsWith("0")|| c.startsWith("1")||c.startsWith("2")||c.startsWith("3")||c.startsWith("4")||
c.startsWith("5")||c.startsWith("6")||c.startsWith("7")||c.startsWith("8")||c.startsWith("9"))
stack.push(Integer.parseInt(c));
else if(c.equals("+")){
int op1 = stack.pop();
int op2= stack.pop();
stack.push(op2+op1);
}
else if(c.equals("-")){
int op1 = stack.pop();
int op2= stack.pop();
stack.push(op2-op1);
}
else if(c.equals("*")){
int op1 = stack.pop();
int op2= stack.pop();
stack.push(op2*op1);
}
else if(c.equals("/")){
int op1 = stack.pop();
int op2= stack.pop();
stack.push(op2/op1);
}
else if(c.equals("%")){
int op1 = stack.pop();
int op2= stack.pop();
stack.push(op1%op2);
}
}
System.out.println(stack.pop());
}
}
Here is the StackTrace
Input your expression using postfix notation
3 14+2*7/
Exception in thread "main" java.lang.NumberFormatException: For input string: "14+2*7/"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at PostFix.main(PostFix.java:18)
If you really have to use StringTokenizer
, construct it like this:
StringTokenizer tokenizer = new StringTokenizer(expr, " +-*/%", true);
The second parameter says that spaces and all the operators are considered delimiters, in addition to spaces. The third parameter says that the delimiters are treated as tokens, so when it sees "+"
, "-"
, etc., it will return that as a string. It will also return spaces, so you have to make sure that when nextToken
returns " "
, you ignore it and don't treat it as an error.