我的驱动程序类编译但不返回预期值

时间:2015-12-09 22:24:09

标签: java stack

好吧,所以当程序运行时没有错误,但是没有返回预期的输出。该程序只是重新打印字符串而不是转换它。这里包含PostfixtoInfix2类的代码。该方法依赖于其他方法正常工作。我无法确定哪种方法运行不正确。欢迎任何想法,更好的编码惯例或解决方案。

import java.util.Stack;
public class PostfixtoInfix2 
  /*
 * This class takes an expression in Infix and translates it to Prefix.
 * */

{
  public String expression;
  public Stack <Character> s= new Stack();


  public String PostfixtoInfix(String e)
  {expression = e;
    String output ="";
    for(int i=0; i < expression.length(); i++)
      {char currentChar = expression.charAt(i);
         if(isOperator(currentChar))
              {while(!s.empty() && s.peek() != '(' && hasHigherPrecedence(s.peek(), currentChar))
                        {output += s.peek();
                         s.pop();
              }
                  s.push(currentChar);
              }
          else if(isOperand(currentChar))
          {output += currentChar;
          }
          else if(currentChar == '(')
          {s.push(currentChar);
          }
          else if(currentChar == ')')
          {while(!s.empty() && s.peek() != ')')
            {output += s.peek();
             s.pop();
             }
          }
          while(!s.empty())
          {output += s.peek();
            s.pop();
          }
    } return output;
  }

public boolean isOperator(char c)
{
if(c =='+' || c=='-' || c=='/' || c=='*' || c== '^')
  return true;
return false;
}

 public boolean isOperand( char c)
 {if(c>='0' && c<='9') return true;
   if(c>= 'a' && c<= 'z') return true;
   if(c>= 'A' && c<= 'Z') return true;
   return false;
 }

 public int getOperatorWeight(char operator)
 {int weight = -1;
   switch (operator)
   {case '+':
     case'-':
     weight =1;
     break;

     case '*':
     case '/':
       weight = 2;
       break;

     case '^':
       weight =3;
   }
   return weight;
 }

 public boolean hasHigherPrecedence(char operator1, char operator2)
 {
 int op1 = getOperatorWeight(operator1);
 int op2 = getOperatorWeight(operator2);
 if(op1==op2)
 {if(isRightAssociative(operator1))return false;
   else return true;
 }
 return op1> op2 ? true : false;
 }

 public boolean isRightAssociative(char op)
 {
 if(op == '^') return true;
 return false;
 } 
}

public class PostfixDemo
{
  public static void main(String args[])
  { PostfixtoInfix2 j = new PostfixtoInfix2();
    System.out.print(j.PostfixtoInfix("3218+-"));
  }
}

1 个答案:

答案 0 :(得分:-2)

public String postfix2Infix(String s) {
    Stack<String> stack = new Stack<>();
    for (int i = 0, len = s.length(); i < len; ++i) {
        char c = s.charAt(i);
        if (isOperator(c)) {
            String r = stack.pop();
            String l = stack.pop();
            stack.push("(" + l + c + r + ")");
        } else
            stack.push(Character.toString(c));
    }
    return stack.pop();
}

public static void mai(String[] args) {
    System.out.println(postfix2Infix("3218+-*"));  // -> (3*(2-(1+8)))
}