I have problem concerning evaluating postfix expression using stack
for(int i=0;i<postfix.length;i++){
System.out.println("iteration:"+(i+1));
if(postfix[i].equalsIgnoreCase("+") || postfix[i].equalsIgnoreCase("-")
|| postfix[i].equalsIgnoreCase("*") || postfix[i].equalsIgnoreCase("/") ) {
num1 = Float.parseFloat((String)out.pop());
System.out.println("pop:"+num1);
num2 = Float.parseFloat((String)out.pop());
System.out.println("pop:"+num2);
if(postfix[i].equalsIgnoreCase("+")) {
temp = num2+num1;
out.push(temp);
System.out.println("push:"+temp);
}
else if(postfix[i].equalsIgnoreCase("-")) {
temp = num2-num1;
out.push((""+temp));
System.out.println("push:"+temp);
}
else if(postfix[i].equalsIgnoreCase("*")) {
temp = num2*num1;
out.push((""+temp));
System.out.println("push:"+temp);
}
else if(postfix[i].equalsIgnoreCase("/")) {
temp = num2/num1;
out.push((""+temp));
System.out.println("push:"+temp);
}
}
else{
System.out.println("push:"+postfix[i]);
out.push(postfix[i]);
}
}
the code works well if i only do operation among two numbers e.g “2 4 +”
but when it becomes like “2 4 + 5 +” the error suddenly appears.. i even put markers.. the prints there to check the flow of my code ..thanks
any help?
On one line
out.push(temp);which is pushing a Float instead fo a String.I suggest you use
with
and
and
As Stack is a legacy class, a better choice would be a Deque, but I assume you don’t need to worry about changing it for this project.