我想制作反向波兰表示法算法,但我的代码不起作用。谁能解释我为什么?在我的代码中,我想使用字符,直到 "/+-*"tokens 。如果此标记是下一个,则进行操作,其中包含 in case 。
import java.util.Stack;
import java.util.StringTokenizer;
import javax.swing.JOptionPane;
public class ONP {
public static void main(String[] args) {
Stack<Double> stack = new Stack<Double>();
double number1;
double number2;
String x = JOptionPane.showInputDialog("Tokens");
StringTokenizer str = new StringTokenizer(x);
while (str.hasMoreElements()) {
str.nextElement();
stack.push((Double) str.nextElement());
for (int i = 0; i < x.length(); i++) {
switch (x.charAt(i)) {
case '+':
number1 = stack.pop();
number2 = stack.pop();
System.out.println(number1 + number2);
break;
case '-':
number1 = stack.pop();
number2 = stack.pop();
System.out.println(number1 - number2);
break;
case '/':
number1 = stack.pop();
number2 = stack.pop();
System.out.println(number1 / number2);
break;
case '*':
number1 = stack.pop();
number2 = stack.pop();
System.out.println(number1 * number2);
break;
}
}
System.out.println(stack.pop());
}
}
}
我想在没有 StringBuilder 或类似的情况下编写它。
输入:
2 2 + 2 / 2 /
输出 :
(2+2) / 2 / 2