Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 堆栈,括号匹配_Java_Linked List_Stack_Postfix Notation_Infix Notation - Fatal编程技术网

Java 堆栈,括号匹配

Java 堆栈,括号匹配,java,linked-list,stack,postfix-notation,infix-notation,Java,Linked List,Stack,Postfix Notation,Infix Notation,所以我正在做一些关于后缀和中缀表达式的家庭作业。我遇到了一点问题,似乎找不到问题所在。我可以让中缀到后缀工作…大部分时间。当我不想打印的时候,我得到了一个(或)打印出来的一些等式。而且,当我没有匹配的括号时,我不会得到我想要的错误 public String Infix(String equation) throws Exception{ Stack stack=new Stack(); boolean parensMatch=false; int priority=0;

所以我正在做一些关于后缀和中缀表达式的家庭作业。我遇到了一点问题,似乎找不到问题所在。我可以让中缀到后缀工作…大部分时间。当我不想打印的时候,我得到了一个(或)打印出来的一些等式。而且,当我没有匹配的括号时,我不会得到我想要的错误

public String Infix(String equation) throws Exception{
    Stack stack=new Stack();
    boolean parensMatch=false;
    int priority=0;
    String temp="";
    for(int i=0; i<equation.length(); i++){
        char c=equation.charAt(i);
        //if the character is equal to left paren, push
        if(c=='('){
            stack.push(c);
        }
        //if the character is equal to right paren, we start popping until we find a match
        else if(c==')'){
            try{
                while(stack.peek()!='('){
                    temp+=stack.pop();
                }

                if(stack.peek()=='('){
                    char ch=stack.pop();
                    parensMatch=true;
                }

                if(parensMatch==false){
                    throw new Exception("Parens Not Match Error");
                }
            }catch(Exception e){
                System.out.println(e);
            }
            parensMatch=false;
        }
        //if the character is equal to an operator, we do some extra work
        //to figure out what is going to happen
        else if(c=='+' || c=='-' || c=='*' || c=='/' || c=='^'){
            char top=stack.peek();
            if(top=='^')
                priority=2;
            else if(top=='*' || top=='/')
                priority=1;
            else
                priority=0;
            if(priority==2){
                if(c=='*' || c=='/'){
                    temp+=stack.pop();
                }
                else if(c=='+' || c=='-'){
                    temp+=stack.pop();
                }
                else{
                    temp+=stack.pop();
                }
            }
            else{
                if(c=='*' || c=='/'){
                    temp+=stack.pop();
                    stack.push(c);
                }
                else if(c=='+' || c=='-'){
                    stack.push(c);
                }
                else{
                    stack.push(c);
                }
            }
        }
        //if the character is a space, we ignore it and move on
        else if(c==' '){
            ;
        }
        //if the character is a letter, we add it to the string
        else{
            temp+=c;
        }
    }
    int len = stack.size();
    for (int j = 0; j < len; j++)
       temp+=stack.pop();
    return temp;
}

要验证括号是否都匹配,可以使用初始值为0的计数器运行数学表达式的字符串输入,如果找到
),则将计数器增加1,如果找到
,则将计数器减少1。如果计数器曾经达到-1,则中断,因为它不是有效的括号匹配。最后,计数器的值应为0。如果不是,则括号不匹配

对于中缀到后缀的情况,这里有一个标准算法:

Define a stack
Go through each character in the string
If it is between 0 to 9, append it to output string.
If it is left brace push to stack
If it is operator *,+,- or / then 
          If the stack is empty push it to the stack
          If the stack is not empty then start a loop:
                             If the top of the stack has higher precedence
                             Then pop and append to output string
                             Else break
                     Push to the stack

If it is right brace then
            While stack not empty and top not equal to left brace
            Pop from stack and append to output string
            Finally pop out the left brace.

好吧,我想给你一些“软件工程”的建议,它最终可以解决你的问题,你可以通过做得“好”学到很多东西

数学表达式,不管你是按前、中、后顺序写的,如果你把它们存储在某种树结构中,看起来总是一样的

然后,如果您想将树结构打印到字符串中,只需遍历整个树,当您将它写入字符串时,它只会在瞬间发生变化(在某些情况下还需要附加大括号)

当您第一次进入该节点时,进行预排序;如果您在离开该节点时进行预排序,则在完成左子节点和后排序时进行预排序

我的忠告是:

类:
Expression
UnaryExpression extends Expression
BinaryExpression extedns Expression
,然后可以生成数字和运算符:
Add extends BinaryExpression

然后您应该有一个类
,它存储
表达式根
,它有方法
printPreOrder()
printInOrder()
printPostOrder()

要创建该树,最好使用
Builder模式
,可以这样使用:

public class Director {
    private IExpressionBuilder builder;

    public ArithmeticExpression construct(String text){
                for (int i=0;i<text.length();i++){
                    if (text.charAt(i) == '+'){
                        builder.buildAddOperator();
                    }
                    ...
                }
    }  
public class InOrderBuilder implements IExpressionBuilder {

    public void buildAddOperator() {
        ...
    }
    ....
}

这并没有解决OP的问题,这就是为什么输出中有一个左括号。您还需要确保计数器永远不会为负!正当字符串
“())(”
最后的计数是0,但括号肯定不平衡。@TedHopp和at mbroshi:感谢您的正确指导和反馈。我已经相应地更新了我的答案。我还需要做些什么来提供正确的答案?在手前仔细检查等式并检查是否有更有效的方法吗匹配参数?现在一切都进行得很顺利。我已经弄明白了。谢谢@awfullyAwesome您预期的后缀输出不正确。后缀符号中没有括号。
public class InOrderBuilder implements IExpressionBuilder {

    public void buildAddOperator() {
        ...
    }
    ....
}