第一次发帖,请告诉我如何改进。
我正在开发一个将中缀表示法转换为后缀然后进行评估的程序。我对后缀的转换进展顺利,但我的评估遇到了一些问题。在下面的代码中,当我尝试将操作数转换为双变量“数字”时,它们不会保持它们的值(参见下面的运行时输出)。这是有问题的方法的一部分(打印语句仅用于调试)。
public boolean evaluatePostfix(StringBuffer postfix)
{
Stack <Double> operand = new Stack <Double>();//stack to hold operand values
double answer = 0; //variable to hold result of expression
boolean error = false; //tests for input error
int pos = 0; //temp veraible stores position in postfix expression
double number = 0; //temp variable to convert char to double. also stores that value for reference
double val1 = 0; //first value for operations
double val2 = 0; //second value for operations
double val3 = 0; //answer for val1 and val2
while (!error && pos < postfix.length())
{
System.out.println(postfix.charAt(pos));
if (postfix.charAt(pos) == ' ')
; //do nothing
else if (Character.isDigit(postfix.charAt(pos)))
{
number = Double.parseDouble(postfix.substring(pos));
System.out.printf ("number = %f", number);
operand.push(number);
}
else
{
val1 = operand.pop();
val2 = operand.pop();
System.out.printf ("val1: %f\tval2: %f\n", val1, val2);
---在运行时--- 1
数字 = 49.000000
8
数字 = 56.000000
+
val1:56.000000
val2:49.000000
val3 = 105.000000
105.0