Search code examples
javaalgorithmpostfix-notationinfix-notation

Infix to postfix convert algorithm error in java


This code has to convert insfix expressions to postfix

  while(!infixStack.isEmpty() && infixStack.top() != '(' && Precedence(infixStack.top(),st)) { 
                postfix += infixStack.top();
                infixStack.pop();
            }

I guess my mistake is in this lines or in the precedence method. Because I give the input : 35+6*2-3/(3*5) and my output is : 356+2*3-35*/ but it has to be : 3562*+335*/-

    public String InfixToPostfix(String element) {

    SLLStack<Character> infixStack = new SLLStack<Character>();
    String postfix = "";

    for(int i = 0 ; i < element.length() ; i++){
        char st = element.charAt(i);

        if(st == ' ' || st == ',') {continue;}

        else if(Operator(st)){

            while(!infixStack.isEmpty() && infixStack.top() != '(' && Precedence(infixStack.top(),st)) { 
                postfix += infixStack.top();
                infixStack.pop();
            }

            infixStack.push(st);
        }

        else if(Operand(st)){
            postfix += st;
        }

        else if (st == '(') {
            infixStack.push(st);
        }

        else if(st == ')')
        {
            while(!infixStack.isEmpty() && infixStack.top() !=  '(') {
                postfix += infixStack.top();
                infixStack.pop();
            }
            infixStack.pop();
        }
    }

    while(!infixStack.isEmpty() && infixStack.top() !=  '(') {
        postfix += infixStack.top();
        infixStack.pop();
    }

    return postfix;
}

public boolean Operand(char st) {
        if(st >= '0' && st <= '9') {return true;}
        else {return false;}
}

public boolean Operator(char st) {
    if(st == '+' || st == '-' || st == '*' || st == '/') {return true;}
    else {return false;}
}

public int OperatorWeight(char st) {
    int weight = -1;
    switch(st)
    {
        case '+':
        case '-':
            weight = 0;
        case '*':
        case '/':
            weight = 1;
    }
    return weight;
}

public boolean Precedence(char operand1, char operand2) {
    int op1Weight = OperatorWeight(operand1);
    int op2Weight = OperatorWeight(operand2);

    if(op1Weight >= op2Weight) {
       return true;
    }

    else {return false;}
}

Solution

  • Theres a problem with the switch statement. I tried this instead and it worked

    public int OperatorWeight(char st) {
    
    
            if(st == '+' || st == '-'){
                return 0;
            }
            else{
                return 1;
            }
    }
    

    or adding a break statement at the end of the first 2 cases would work