我正在努力完成一项任务。我有一个没有括号的“计算器”,它将这个中缀表达式转换为后缀,并试图处理运算符堆栈中存在运算符的情况。
我指的是这个算法:http ://scriptasylum.com/tutorials/infix_postfix/algorithms/infix-postfix/index.htm
现在我的转换器在堆栈顶部和扫描字符优先的情况下存在问题。我有一个while循环来处理这个过程,它会弹出更高优先级的选项,或者它会简单地将它推到堆栈的顶部。但是,它似乎不想离开那个 while 循环。只有当堆栈不是空的并且堆栈顶部优先于扫描的字符时,它才应该在该循环中。
但是,stack.isEmpty
目前在调试器中根本没有改变。
这是我的代码:
import java.util.Stack;
public class Calculator{
public static String[] convert(String expression){
Stack<String> ops = new Stack<String>();
String[] eval = expression.split(" ");
String[] post = new String[eval.length];
int postIndex = 0;
int stackSize = 0;
for(int i = 0; i < eval.length; i++){
if(!isOperator(eval[i])){
post[postIndex] = eval[i];
postIndex++;
}
else if(isOperator(eval[i]) && ops.empty()){
ops.push(eval[i]);
stackSize++;
}
else if(isOperator(eval[i]) && (!ops.empty())){
//ITS EMPTY, SO WHY DO YOU TRY TO GO HERE???
while( (precedence(ops.peek(),eval[i]) && (stackSize > 0)) ) {
if(precedence(ops.peek(),eval[i])){
post[postIndex] = ops.pop();
stackSize--;
postIndex++;
}
else{
ops.push(eval[i]);
stackSize++;
}
}
}
}
while(stackSize > 0){
post[postIndex] = ops.pop();
stackSize--;
}
return post;
}
public static double evaluatePostfix(String[] postfixExpression) {
Stack<Double> opStack = new Stack<Double>();
for(int i = 0; i < postfixExpression.length; i++){
if(!isOperator(postfixExpression[i])){
opStack.push(Double.parseDouble(postfixExpression[i]));
}
else{
double left= opStack.pop();
double right= opStack.pop();
opStack.push(evaluateWithOperator(postfixExpression[i],right,left));
}
}
return opStack.pop();
}
private static boolean isOperator(String s) {
return "+-*/".contains(s);
}
private static boolean precedence(String opA, String opB){
if((opA.equals("*") || opA.equals("/")) && (opB.equals("+") || opB.equals("-"))) {
return true;
}
return false;
}
private static double evaluateWithOperator(String operator, double operandA, double operandB) {
switch(operator) {
case "+":
return operandA + operandB;
case "-":
return operandA - operandB;
case "*":
return operandA * operandB;
case "/":
return operandA / operandB;
default:
return -1;
}
}
public static void main(String[] args){
String expe = "2 * 3 + 5 * 5 * 2 / 10 - 1 * 1";
evaluatePostfix(convert(expe));
}
}