我需要编写一个程序,将中缀表达式转换为后缀表达式。但是当我使用括号时,遇到了问题。例如,当我输入"a + (c - h) / (b * d)"时,输出结果是"ac+h-b/d*",而实际上应该是"a c h - b d * / +." 希望能得到帮助。谢谢。
import java.util.Scanner;
import java.util.Stack;
public class PostfixConverter {
static private String expression;
private Stack<Character> stack = new Stack<Character>();
public PostfixConverter(String infixExpression) {
expression = infixExpression;
}
public String infixToPostfix() {
String postfixString = "";
for (int index = 0; index < expression.length(); ++index) {
char value = expression.charAt(index);
if (value == '(') {
} else if (value == ')') {
Character oper = stack.peek();
while (!(oper.equals('(')) && !(stack.isEmpty())) {
stack.pop();
postfixString += oper.charValue();
}
} else if (value == '+' || value == '-') {
if (stack.isEmpty()) {
stack.push(value);
} else {
Character oper = stack.peek();
while (!(stack.isEmpty() || oper.equals(('(')) || oper.equals((')')))) {
stack.pop();
postfixString += oper.charValue();
}
stack.push(value);
}
} else if (value == '*' || value == '/') {
if (stack.isEmpty()) {
stack.push(value);
} else {
Character oper = stack.peek();
while (!oper.equals(('+')) && !oper.equals(('-')) && !stack.isEmpty()) {
stack.pop();
postfixString += oper.charValue();
}
stack.push(value);
}
} else {
postfixString += value;
}
}
while (!stack.isEmpty()) {
Character oper = stack.peek();
if (!oper.equals(('('))) {
stack.pop();
postfixString += oper.charValue();
}
}
return postfixString;
}
public static void main(String[] args) {
System.out.println("Type an expression written in Infix notation: ");
Scanner input = new Scanner(System.in);
String expression = input.next();
PostfixConverter convert = new PostfixConverter(expression);
System.out.println("This expression writtien in Postfix notation is: \n" + convert.infixToPostfix());
}
}