I am working on converting Infix to Postfix and then evaluating the Postfix expression. However, when I compile the code I get a few error messages. I am not sure what I am doing wrong. Your input will be greatly appreciated. I've tried several things but it doesn't seem to make it work the way it should.
import java.util.*;
public class calculator {
private String infix;
private String postfix = " ";
// public calculator(String in) {
// input = in;
// int SIZE = input.length();
// }
public String toPostfix(String infix) {
String expression;
String postfix = " ";
Stack operatorStack = new Stack();
StringTokenizer s = new StringTokenizer(infix);
while (s.hasMoreTokens()) {
expression = s.nextToken();
if (Character.isDigit(expression.charAt(0)))
postfix = postfix + " " + (Integer.parseInt(expression));
else if (expression.equals("("))
{
Character operator = new Character('(');
operatorStack.push(operator);
} else if (expression.equals(")"))
{
while (((Character) operatorStack.peek()).charValue() != '(') {
postfix = postfix + " " + operatorStack.pop();
}
operatorStack.pop();
} else
{
while (!operatorStack.isEmpty()
&& !(operatorStack.peek()).equals("(")
&& prec(expression.charAt(0))
<= prec(((Character) operatorStack
.peek()).charValue()))
postfix = postfix + " " + operatorStack.pop();
Character operator = new Character(expression.charAt(0));
operatorStack.push(operator);
}
}
while (!operatorStack.isEmpty())
postfix = postfix + " " + operatorStack.pop();
return postfix;
}
private static int prec(char x) {
if (x == '+' || x == '-')
return 1;
if (x == '*' || x == '/' || x == '%')
return 2;
return 0;
}
public int evaluate(String postfix) {
int a;
int b;
int result = 0;
Stack<Integer> myStack = new Stack<Integer>();
for (int i = 0; i < postfix.length(); i++) {
char ch = postfix.charAt(i);
if (ch >= '0' && ch <= '9') {
myStack.push((int) (ch - '0'));
} else {
switch (ch) {
case '+':
a = myStack.pop();
b = myStack.pop();
result = a + b;
myStack.push(result);
break;
case '-':
a = myStack.pop();
b = myStack.pop();
result = a - b;
myStack.push(result);
break;
case '*':
a = myStack.pop();
b = myStack.pop();
result = a * b;
myStack.push(result);
break;
case '/':
a = myStack.pop();
b = myStack.pop();
result = a / b;
myStack.push(result);
break;
}
myStack.push(result);
}
}
myStack.push(result);
return result;
}
}

New Topic/Question
Reply



MultiQuote




|