I need to evaluate postfix expressions using a linked list stack. I think i need some help with the algorithm. I write 13+
as input but i get 100
as output.
PostfixCalculator Class:
public class PostfixCalculator{
String expression;
MyStack stack = new MyStack<Double>();
public PostfixCalculator(String postFixExpression)
{
expression = postFixExpression;
}
public String calculate()
{
String output = "";
char character = ' ';
double digit = 0;
for(int x = 0; x < expression.length(); x++)
{
if(Character.isDigit(expression.charAt(x))) {
digit = expression.charAt(x);
}
character = expression.charAt(x);
if(expression.charAt(x) == digit)
{
stack.push(digit);
}
else if(character == '*')
{
double tmp = (double) stack.pop() * (double) stack.pop();
stack.push(tmp);
}
else if(character == '/')
{
double tmp = (double) stack.pop() / (double) stack.pop();
stack.push(tmp);
}
else if(character == '+')
{
double tmp = (double) stack.pop() + (double) stack.pop();
stack.push(tmp);
}
else if(character == '-')
{
double tmp = (double) stack.pop() - (double) stack.pop();
stack.push(tmp);
}
}
while(!stack.isEmpty())
{
output = output + (double) stack.pop();
}
return output;
}
}
PostfixCalculatorTest Class:
import java.util.Scanner;
public class PostfixCalculatorTest
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Type the postfix expression that you want to evaluate");
String expression = input.next();
PostfixCalculator calculator = new PostfixCalculator(expression);
System.out.println(calculator.calculate());
}
}
First this
if(Character.isDigit(expression.charAt(x))) {
digit = expression.charAt(x);
}
saves the decimal ASCII value of the char at the position x as double, for the char '1'
it is 49
, for '3'
it is 51
, hence you get 100
as result
it should be
digit = Double.parseDouble("" + expression.charAt(x));
i.e. parse the char to get the double value it represents.
Here is the small change
character = expression.charAt(x);
if(Character.isDigit(character)) {
digit = Double.parseDouble("" + character);
stack.push(digit);
}
then it would work for 13+
and give 4
as result.
Those line can be removed:
character = expression.charAt(x);
if(expression.charAt(x) == digit)
{
stack.push(digit);
}