发布的代码适用于操作,但如果运算符和操作数之间没有间距,则不会工作。
我得到了 4 个表达式来计算
10 2 8 * + 3 -
3 14+2*7/
4 2 + 3 15 1 - * +
1 2 + 3 % 6 - 2 3 + /
(间距很重要)
表达式二是不会使用我当前的计算器计算的
这是我的代码
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());
}
}
这是堆栈跟踪
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)