设置操作的优先级计算器应用

问题描述

我正在研究 app 计算器,使用 Stack,我无法为操作设置优先级。

使用 HashMap 表示优先级:

 private void addPriorities() {
        priorities.put("*",3);
        priorities.put("/",3);
        priorities.put("+",2);
        priorities.put("-",2);
        priorities.put("0",0);
        priorities.put("1",0);
        priorities.put("2",0);
        priorities.put("3",0);
        priorities.put("4",0);
        priorities.put("5",0);
        priorities.put("6",0);
        priorities.put("7",0);
        priorities.put("8",0);
        priorities.put("9",0);
    }

methodsplit String 在两个 Stacks 中,app 已经可以工作了,问题是操作的优先级不工作:

 public void convertString() {
        arr = expression.split("(?<=[\\d.])(?=[^\\d.])|(?<=[^\\d.])(?=[^\\d.])|(?<=[^\\d.])(?=[\\d.])");

        for (int i = 0; i < arr.length; i++) {
            if (arr[i].matches(("[0-9]*\\.?[0-9]*"))) {
                digitStack.push(arr[i]);
            }else  if (arr[i].matches("[(]")) {
                characterStack.push(arr[i]);
            }else if (arr[i].matches("[)]")){
                while (!characterStack.peek().matches("[(]")){
                    digitStack.push(characterStack.pop());
                    if (characterStack.peek().matches("[(]")){
                        characterStack.pop();
                        break;
                    }
                }
            } else if (arr[i].matches("[+=\\-*/^]+")) {
                characterStack.push(arr[i]);
            }
        }
        unionRevers();
    }

在这个地方:

 } else if (arr[i].matches("[+=\\-*/^]+")) {
                characterStack.push(arr[i]);
            }

应该是这样的 - 得到 NullPointerException:

 } else if (arr[i].matches("[+=\\-*/^]+") && priorities.get(arr[i]) > priorities.get(characterStack)) {
        while (arr[i].matches("[+=\\-*/^]+") && priorities.get(arr[i]) > priorities.get(characterStack)){
            digitStack.push(characterStack.pop());
            break;
        }
    }
}

使用 Reverse Polish notationStack

如何设置优先级?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)