First time posting so please inform me of how to improve.
I'm working on a program to convert infix notation to postfix and then evaluate. My conversion to postfix went well, but I'm having some trouble with my evaluation. In the code below, when I try to convert the operands into a double variable 'number' they don't maintain their value (see runtime output below). Here is part of the method in question (the print statements are for debugging only).
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);
---At runtime--- 1
number = 49.000000
8
number = 56.000000
+
val1: 56.000000
val2: 49.000000
val3 = 105.000000
105.0
Replace:
number = postfix.charAt(pos);
with:
number = Double.parseDouble(Character.toString(postfix.charAt(pos)));
The Double.parseDouble method converts the string in double:
Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.
(from Javadoc)
If you split the String with postfix.toString.split(" ") and then iterate on the string[] you will be able to parse also double values (like "8.4567"):
String[] sa = postfix.toString().split(" ");
for (String string : sa) {
.... omissis ...
otherwise your code will be correct only parsing single digit integer values.