我正在尝试创建一个采用中缀表示法并打印出其后缀形式的程序。我的问题是输出仍然是其中缀形式,因此+ b * c输出为+ b * c。我相信我的问题在于我的第一个while循环。我在while循环中的目标是,如果字符是运算符,那么当堆栈不为空时,我的优先级方法被调用,它应该弹出并打印出更大值的运算符,然后查看堆栈的顶部以检查优先级。我把stack.push()方法放在while循环之外。我希望通过这样做,在优先级建立之后或者如果堆栈为空,操作员将被推入堆栈。我的第二个while循环应该弹出并打印出堆栈中剩下的任何东西。感谢您提供给我的任何帮助,我感谢人们花时间指导像我这样的编程新手。这是我到目前为止的代码:
import java.util.*;
public class PostfixConverter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Stack<Character> stack = new Stack<Character>();
System.out.print("Enter infix expression: ");
String expression = new String(sc.nextLine());
for (int i = 0; i < expression.length(); i++) {
/*
* ch as a variable in place of expression.charAt(i) just seems like
* a good idea, ch is easier to write
*/
char ch = expression.charAt(i);
/*
* I hope that this prints out anything that is not a parentheses or
* an operator
*/
if (ch != '(' & !(isOperator(ch)))
System.out.print(ch);
if (ch == '(') {
/*
* This is to push '(' onto the stack
*/
stack.push(ch);
} else if (ch == ')') {
stack.pop();
}
/*
* If the character is an operator, I want to enter into a while
* loop
*/
if (isOperator(ch)) {
/*
* This while loop should check for operator priority, pop
* an operator if it is greater than the operator being
* pushed onto the stack then peek at the top of the stack
*/
while (!(stack.isEmpty())) {
if (priority(ch) <= priority(stack.peek()))
System.out.print(stack.pop());
stack.peek();
}
stack.push(ch);
}
while (!(stack.isEmpty())) {
System.out.print(stack.pop());
}
}
}
/*
* Both of my methods below use a switch statement to check priority and
* whether a char is an operator
*/
public static int priority(char operator) {
switch (operator) {
case '+':
return 1;
case '-':
return 1;
case '*':
return 2;
case '/':
return 2;
case '^':
return 3;
default:
return 0;
}
}
public static boolean isOperator(char operator) {
switch (operator) {
case '+':
return true;
case '-':
return true;
case '*':
return true;
case '/':
return true;
case '^':
return true;
default:
return false;
}
}
}
答案 0 :(得分:0)
您正在为输入表达式的每个字符打印和清除堆栈。这可能不是你想要的。
你的解析循环中有这个:
while (!(stack.isEmpty())) {
System.out.print(stack.pop());
}
将那个位置基本上只打印出当前字符(刚刚被推入空堆栈)然后清除堆栈(通过弹出所有内容直到它为空)。
你可能意味着将它移到循环之外,在它之后。
你想解析整个表达式并构建堆栈,然后打印它,所以你应该在你的代码中完成它。