4

嘿嘿。我正在尝试实现一个 java 代码,它将根据我的输入返回真或假。例如,如果我有 true AND NOT( false AND true) AND NOT TRUE 它应该返回 FALSE

我试图解析我的输入字符串并首先将元素重新排序为波兰符号,然后评估波兰形式。如果我没有,它可以完美运行

但是,如果我有 true AND NOT( (false or false) AND (true OR false)) AND NOT TRUE 它返回 TRUE 但它应该返回 false。

在我运行 getPolishForm() 函数后,我的 RPF 看起来像这样

真假假或真假或与真非与非与

我看到问题出在第二个不是因为它否定了所有这部分((假或假)AND(真或假))而不是真的,但它应该只否定 paranthesys 中的内容。

这是以 polsih 形式返回字符串列表的函数

  ArrayList<String> getPolishForm() {
    ArrayList<String> postFix = new ArrayList<String>();
    if (infixForm == null)
        return null;
    Stack<String> stack = new Stack<String>();
    for (int i = 0; i < infixForm.size(); i++) {
        switch (new Priority(infixForm.get(i)).getValue()) {
        case 3:
            while (!stack.empty() && (stack.peek().equals("AND"))) {
                postFix.add(stack.pop());
            }
            stack.push(infixForm.get(i));
            break;
        case 4:
            stack.push(infixForm.get(i));
            break;
        case 1:
            stack.push(infixForm.get(i));
            break;
        case 2:
            while (!stack.empty() && !stack.peek().equals("LPARAN")) {
                postFix.add(stack.pop());
            }
            stack.pop();
            break;
        case 5:
            stack.push(infixForm.get(i));
            break;

        default:
            postFix.add(infixForm.get(i));
            break;
        }
    }
    while (!stack.empty()) {
        postFix.add(stack.pop());
    }

    return postFix;
}

这是评估 RPF 的函数

Boolean getResult() {
    Stack<Boolean> stack = new Stack<Boolean>();
    boolean result = false;

    for (int i = 0; i < postFix.size(); i++) {
        if (isExpression(postFix.get(i))) {
            stack.push(new ReMatcher(postFix.get(i), tags).isMatch());//this line processes the string from the infixForm and returns a boolean

        } else {
            boolean op1 = stack.pop();
            try {
                boolean op2 = stack.pop();

                String operator = postFix.get(i);
                if (operator.equals("NOT")) {
                    op1 = !op1;
                    i++;
                    operator = postFix.get(i);
                }

                if (operator.equals("OR") )
                    result = op1 || op2;

                } else if (operator.endsWith("AND") )
                    result = op1 && op2;

            } catch (EmptyStackException e) {
                result = !op1;
            }
            stack.push(result);
        }
    }
    return stack.pop();

提前谢谢你:D

4

0 回答 0