I'm working on a project that solves postfix expressions. I'm having trouble figuring out the exception handling or whether or not I'm event using the stack correctly. Some pointers would be greatly helpful. Here's the code:
import java.util.Stack;
import java.util.EmptyStackException;
import java.util.*;
public class Solve {
int result, num1, num2, stackNum;
MyStack<Integer> stack;
char c;
String expression, delimiter;
public Solve()
{
result = 0;
num1 = 0;
num2 = 0;
delimiter = " ";
c = ' ';
stackNum = 0;
stack = new MyStack<Integer>();
}
public String evaluate(String expression) throws EmptyStackException
{
StringTokenizer st = new StringTokenizer(expression);
while (st.hasMoreTokens())
{
//String[] eToken = expression.split(" ");
try
{
//for (int i = 0; i < expression.length(); ++i)
//{
if (st.nextToken().charAt(0) != '+' && st.nextToken().charAt(0) != '-' && st.nextToken().charAt(0) != '*' && st.nextToken().charAt(0) != '/')
{
stackNum = Integer.parseInt(st.nextToken());
stack.push(stackNum);
}
else
{
c = st.nextToken().charAt(0);
num1 = stack.pop();
num2 = stack.pop();
if (c == '+')
stack.push(num1 + num2);
else if (c == '-')
stack.push(num1 - num2);
else if (c == '*')
stack.push(num1 * num2);
else if (c == '/')
stack.push(num1 / num2);
}
//}
}
catch (EmptyStackException e)
{
throw new EmptyStackException();
}
}
result = stack.pop();
return String.valueOf(result);
}
}
Aucun commentaire:
Enregistrer un commentaire