java—为操作设置优先级计算器应用程序

eulz3vhy  于 2021-06-29  发布在  Java
关注(0)|答案(0)|浏览(192)

我在工作 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);
    }
``` `method` 至
split `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]);
}

应该是这样的-get 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 notation` ,和 `Stack` .
如何设置优先级?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题