Reputation:
I'm trying to evaluate a postfix expression.
My code compiles but the final answer is wrong.
I tried looking at other answers but they weren't in Java.
public class PA36Stack
{
public static void main(String[] args)
{
PA31Stack an = new PA31Stack(12);
String g = "234*+";
int x = evaluate(an, g);
System.out.print(x);
}
public static int evaluate(PA31Stack b, String g)
{
int temp = 0;
for (int i = 0; i < g.length(); i++)
{
if (g.charAt(i) != '+' && g.charAt(i) != '-' && g.charAt(i) != '*' && g.charAt(i) != '/')
{
b.push(g.charAt(i));
}
else
{
int a = b.pop();
int c = b.pop();
if (g.charAt(i) == '+')
{
temp = a + c;
b.push(temp);
}
//nextone
if (g.charAt(i) == '-')
{
temp = (c - a);
b.push(temp);
}
//two
if (g.charAt(i) == '*')
{
temp = (c * a);
b.push(temp);
}
//three
if (g.charAt(i) == '/')
{
temp = (c / a);
b.push(temp);
}
}
}
return b.pop();
}
}
Upvotes: 0
Views: 8686
Reputation: 17595
This is because you are using the ASCII values of the chars representing the numbers for the calculation.
Basically you need to convert the char representing the number to the int it actual represents, i.e. make of '1'
a 1
and of '2'
a 2
an so on.
To get around this problem you need to substract the ascii value of the char '0'
while pop-ind out of the stack to get the real integer value and adding it on push.
Since you have not posted the code of your stack, I've edited it to use a java.util.Stack<Character>
and got the correkt result of 14
for the expression 234*+
public static int evaluate(Stack<Character> b, String g) {
int temp = 0;
for (int i = 0; i < g.length(); i++) {
if (g.charAt(i) != '+' && g.charAt(i) != '-' && g.charAt(i) != '*'
&& g.charAt(i) != '/') {
b.push(g.charAt(i));
} else {
int a = b.pop() - '0';
int c = b.pop() - '0';
if (g.charAt(i) == '+') {
temp = a + c;
b.push((char)(temp + '0'));
}
// nextone
if (g.charAt(i) == '-') {
temp = (c - a);
b.push((char)(temp + '0'));
}
// two
if (g.charAt(i) == '*') {
temp = (c * a);
b.push((char)(temp + '0'));
}
// three
if (g.charAt(i) == '/') {
temp = (c / a);
b.push((char)(temp + '0'));
}
}
}
return b.pop() - '0';
}
Upvotes: 1