import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
public class PostFixEval {
static Scanner input = new Scanner(System.in);
static String expression;
static Stack<Integer> calcStack = new Stack<Integer>();
static List<String> expressionList = new ArrayList<String>();
static boolean flag = false;
public static void main(String[] args) {
System.out.print("Enter Your Expression: ");
while (flag == false){
expression = input.next();
System.out.println("");
expression = whiteSpaceRemover(expression);
if (expression.substring(expression.length() - 1) == ";"){
expressionList.add(expression);
} else if (expression.substring(expression.length() - 1) == "@"){
expressionList.add(expression);
flag = true;
} else {
System.out.println("Not a valid expression (must end in a ; or a @)");
}
}
calc(expressionList);
}
public static void calc(List<String> list){
for (int i=0;i<list.size();i++){
String currentExpression = list.get(i);
for (char ch : currentExpression.toCharArray()){
if (ch == '+'){
calcStack.push(calcStack.pop()+calcStack.pop());
System.out.println("Pop R1");
System.out.println("Pop R2");
System.out.println("ADD R1, R2");
System.out.println("PUSH R1");
}
else if (ch == '-')
{
int temp = calcStack.pop();
calcStack.push(calcStack.pop() - temp);
System.out.println("Pop R2");
System.out.println("Pop R1");
System.out.println("SUB R1, R2");
System.out.println("PUSH R1");
}
else if (ch == '*')
{
calcStack.push(calcStack.pop() * calcStack.pop());
System.out.println("Pop R1");
System.out.println("Pop R2");
System.out.println("MULT R1, R2");
System.out.println("PUSH R1");
}
else if (ch == '/')
{
int temp = calcStack.pop();
if(temp != 0){
calcStack.push(calcStack.pop() / temp);
System.out.println("Pop R1");
System.out.println("Pop R2");
System.out.println("DIV R1, R2");
System.out.println("PUSH R1");
}else{
System.out.println("CANNOT DIVIDE BY ZERO");
break;
}
}
else if
{
int num = Integer.parseInt(ch);
}
}
}
}
public static String whiteSpaceRemover(String express){
return express.replaceAll(" ","");
}
}
我一直在研究逆波兰表示法计算器,但遇到了问题。我意识到我无法将数字添加到堆栈中,因为我的代码分别遍历每个表达式的每个字符。我考虑过将每个数字添加到一个数组中,然后将其转换为一个 int,但我不确定我将如何去做。任何帮助将不胜感激。
谢谢。