java - java 中的 bc 实用程序,在某些情况下会失败

标签 java bc postfix-operator

我正在尝试用 java 编写简单的 bc 实用程序。我的程序在大多数情况下都运行良好,但对于表达式 4+4*3-3-2-1/3 却失败了。基本上是连续的 - 运营商。不确定我是否涵盖了所有边缘情况。任何让它变得更好的建议都会非常有帮助。谢谢

//ENUM for operations allowed.
private enum Operators {
    ADD         (1, "+"),
    SUBTRACT   (1, "-"),
    MULTIPLY    (2, "*"),
    DIVIDE      (2, "/");

    String operator;
    // Operator priority
    int weight;
    Operators(int w, String o) {
        this.operator = o;
        this.weight = w;
    }

    public String getOperator() {
        return operator;
    }

    public int getWeight() {
        return weight;
    }
}
// Stack and Queue to convert expression to postfix
LinkedList<String> resultQueue = new LinkedList<String>();
Stack<Operators> operatorStack = new Stack<Operators>();
//Stack to evaluate postfix expression
Stack<Integer> evalStack = new Stack<Integer>();

public int eval(String exp) {
    char[] expChar = exp.toCharArray();
    int i = 0;
    StringBuilder sb = new StringBuilder();
    while (i < expChar.length){
        if (expChar[i] >= '0' && expChar[i] <= '9') {
            sb.append(expChar[i]);

            if (i == expChar.length - 1) {
                resultQueue.add(sb.toString());
                while (!operatorStack.isEmpty()){
                    resultQueue.add(operatorStack.pop().getOperator());
                }
            }
        } else if (expChar[i] == '+' || expChar[i] == '-' || expChar[i] == '/' || expChar[i] == '*'){
            if (sb.length() > 0) {
                resultQueue.add(sb.toString());
                sb = new StringBuilder();
            }
                pushOperator(expChar[i]);
        } else
        return 0;
        i++;
    }
    for (String r : resultQueue){
        if (r.charAt(0) > '0' && r.charAt(0) < '9'){
            evalStack.push(Integer.valueOf(r));
        }else {
            try {
                int op2 = evalStack.pop();
                int op1 = evalStack.pop();
                if (r.charAt(0) == '+')
                    evalStack.push(Integer.valueOf(op1+op2));
                else if (r.charAt(0) == '-')
                    evalStack.push(Integer.valueOf(op1-op2));
                else if (r.charAt(0) == '/')
                    evalStack.push(Integer.valueOf(op1/op2));
                else if (r.charAt(0) == '*')
                    evalStack.push(Integer.valueOf(op1*op2));
            } catch (Exception e){
                System.out.println("Parse Error");
                return 0;
            }
        }
    }
    int result=0;
    try{
        result = evalStack.pop();
    }catch (Exception e){
        System.out.println("Parse Error");
    }

    return result;
}

private void pushOperator(char c) {
    Operators val = getOperator(c);
    if (operatorStack.isEmpty() || val.getWeight() >= operatorStack.peek().getWeight()){
        operatorStack.push(val);
    } else {
        while (!operatorStack.isEmpty() && val.getWeight() <= operatorStack.peek().getWeight()){
            resultQueue.add(operatorStack.pop().getOperator());
        }
        operatorStack.push(val);
    }
}

private Operators getOperator(char c) {
    for (Operators o: Operators.values()){
        if (o.getOperator().equals(String.valueOf(c)))
            return o;
    }
    throw new IllegalArgumentException("Operator not supported");
}

public static void main(String[] args) {

    BC bc = new BC();
    System.out.println("Please enter expression: ");
    Scanner scn = new Scanner(System.in);
    String exp = scn.nextLine();
    //remove white spaces
    exp = exp.replaceAll(" ", "");
    System.out.println("Result: " + bc.eval(exp));
    scn.close();
}

最佳答案

问题在于,对于连续的减法运算,您计算的方向是错误的。您从右到左计算,而您需要从左到右计算。

如果您在堆栈上有操作符 12 3 2 0 - - - 您的计算效率很高

12 - (3 - (2 - 0)) = 11

正确的应该是

12 - (3 + 2 + 0) = 7

一种可能的修复方法是。在开始计算之前,您需要将堆栈上的操作数更改为 12 3 2 0++ -

请参阅此代码段,它可以在计算循环之前执行。

// your code
...
    }
    i++;
}

for (i = 0; i < resultQueue.size() - 1; i++) {
    if ("-".equals(resultQueue.get(i)) && "-".equals(resultQueue.get(i+1))) {
        resultQueue.set(i, "+");
    }
}

// your code
for (String r : resultQueue) {
    if (r.charAt(0) > '0' && r.charAt(0) < '9') {
...

关于java - java 中的 bc 实用程序,在某些情况下会失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31175637/

相关文章:

java - 在插入数据库期间如何同时启动和 sleep 多个线程

java - 从一点旋转正交相机 (LibGdx)

bash - 在 bash 中使用 bc 的力量

java - 如何解决大小为0的android.database.CursorIndexOutOfBoundsException : Index 0 requested,

java - 多维数组行到单数组java

linux - awk 或 bc 哪个对于浮点运算更有效?

linux - 如果同一行有 2 个字段匹配,则从同一列减去 2 个值

c - 类型转换指针的增量如何工作?

java - 这里发生了什么 : sum += i++;?

c++ - 前缀和后缀运算符 C++