public static StringBuffer infixToPostfix(StringBuffer infix) throws InvalidCharacterException
{
StringBuffer postfix = new StringBuffer("");
Stack<String> myStack = new Stack<String>();
myStack.push("(");
infix.append(')');
for(int i = 0; i < infix.length(); i++)
{
if(infix.charAt(i) == ' ')
{
//System.out.println("Space!");
}
else if(Character.isDigit(infix.charAt(i)) == true)
{
postfix.append(infix.charAt(i) + " ");
}
else if(infix.charAt(i) == '(')
{
myStack.push("(");
}
else if(infix.charAt(i) == ')')
{
while(myStack.peek()!="(")
{
postfix.append(myStack.pop() + " ");
}
myStack.pop();
}
else if(isOperator(infix.charAt(i) + "") == true)
{
String peekedItem = myStack.peek();
if(isOperator(peekedItem) == true)
{
if(getPrecedence(infix.charAt(i) + "") <= getPrecedence(peekedItem))
{
String poppedOp = myStack.pop();
if(poppedOp == "+")
{
postfix.append("+ ");
}
else if(poppedOp == "-")
{
postfix.append("- ");
}
else if(poppedOp == "*")
{
postfix.append("* ");
}
else if(poppedOp == "/")
{
postfix.append("/ ");
}
else if(poppedOp == "%")
{
postfix.append("% ");
}
String op = String.valueOf(infix.charAt(i));
myStack.push(op);
}
}
else if(isOperator(peekedItem)==false)
{
String op = String.valueOf(infix.charAt(i));
myStack.push(op);
}
}
else
throw new InvalidCharacterException(infix.charAt(i));
}
return postfix;
}
public static double evaluatePost(StringBuffer postfix)
{
String str = new String(postfix);
str = str.replaceAll(" ", "");
postfix = new StringBuffer(str);
postfix.append(")");
Stack<Double> anotherStack = new Stack<Double>();
double answer = 0;
for(int k = 0; postfix.charAt(k) != ')'; k++)
{
if(Character.isDigit(postfix.charAt(k)) == true)
{
anotherStack.push(Double.parseDouble(postfix.charAt(k)+""));
}
else if(isOperator(postfix.charAt(k)+"")==true)
{
double x = anotherStack.pop();
double y = anotherStack.pop();
char op = postfix.charAt(k);
if(op=='+')
{
answer = (x+y);
anotherStack.push(answer);
answer = 0;
}
else if(op=='-')
{
answer = (y-x);
anotherStack.push(answer);
answer = 0;
}
else if(op=='*')
{
answer = (x*y);
anotherStack.push(answer);
answer = 0;
}
else if(op=='/')
{
answer = (y/x);
anotherStack.push(answer);
answer = 0;
}
else if(op=='%')
{
answer = (x%y);
anotherStack.push(answer);
answer = 0;
}
}
}
double finalAnswer = anotherStack.pop();
return finalAnswer;
}发布于 2013-11-21 04:01:19
在进行字符串比较时,*不要使用== *
换行:
if(poppedOp == "+") {
postfix.append("+ ");
}
.....成为
if("+".equals(poppedOp)) {
postfix.append("+ ");
}
.....发布于 2013-11-21 09:56:29
使用开关代替那些级联的ifs。
将所有if(foo == true)替换为if(foo)
https://codereview.stackexchange.com/questions/35798
复制相似问题