在java中使用postix转换算法错误

时间:2014-11-12 21:17:28

标签: java algorithm postfix-notation infix-notation

此代码必须将insfix表达式转换为postfix

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

我想我的错误在于这一行或在优先级方法中。因为我给出输入:35 + 6 * 2-3 /(3 * 5),我的输出是:356 + 2 * 3-35 * /但它必须是: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;}
}

2 个答案:

答案 0 :(得分:2)

切换语句存在问题。我尝试了这个而且它有效

public int OperatorWeight(char st) {


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

或在前两个案例结束时添加break语句将起作用

答案 1 :(得分:0)

你错过了switch语句中的break语句:

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

您也可以使用默认声明

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