I want to create a Postfix Evaluator that works with multidigits and decimal numbers. The program works with multidigits but it does not with decimals. How can I make this? I have used the infix expression: "10 + 20 * ( 50 / 3 ) + 4", which in postfix is "10 20 50 3 / * + 4 +". As a result I have got 347.33333333333337, which is correct. I just need the evaluator to work with decimal numbers.
public class EvaluarExpresion {
public static double evaluaExpresion (String postfija) {
MyStack<Double> stack = new MyStack<Double>();
//String postfija= expresionPostFijo();
for(int i = 0; i < postfija.length(); i++) {
char c = postfija.charAt(i);
if(c == ' ') {
continue;
}else if(Character.isDigit(c) || c == '.') {
int n = 0;
int divider =1;
boolean hasDecimal = false;
while(Character.isDigit(c) || c == '.') {
if(c == '.') {
hasDecimal = true;
} else {
if(hasDecimal) {
divider *=10;
}
n = n*10 + (int)(c-'0');
c = postfija.charAt(i);
}
i++;
}
i--;
stack.push((double) n);
} else {
Double val1 = stack.pop();
Double val2 = stack.pop();
switch(c)
{
case '+':
stack.push(val2+val1);
break;
case '-':
stack.push(val2- val1);
break;
case '/':
stack.push(val2/val1);
break;
case '*':
stack.push(val2*val1);
break;
case '^':
stack.push(Math.pow(val2, val1));
break;
}
}
}
return stack.pop();
}
public static void main(String[] args) {
// This is an example of an infix expression String dato = "10 + 20 * ( 50 / 3 ) + 4";
//The expression provided below is a postfix expression
System.out.println(evaluaExpresion("10 20 50 3 / * + 4 +"));
//The result is 347.33333333333337 which is correct
}
}
There are a number of ways this can be done. What you need to do is look for the ' .
' character, and start some process for dividing by powers of ten once you find a decimal point. The following way should work, and gets all of the division done in one step, reducing round-off error:
} else if (Character.isDigit(c) || c == '.') {
int n = 0;
int divider = 1;
boolean hasDecimal = false;
while (Character.isDigit(c) || c == '.') {
if (c == '.') {
hasDecimal = true;
} else {
if (hasDecimal) {
divider *= 10;
}
n = n * 10 + (int) (c - '0');
c = postfija.charAt(i);
}
i++;
}
i--;
stack.push((double) n / divider);
} else { // etc...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.