我正在开发一个解决后缀表达式的项目。我无法搞清楚异常处理或我是否正确使用堆栈事件。一些指针会非常有帮助。这是代码:
import java.util.Stack;
import java.util.EmptyStackException;
import java.util.*;
公共课解决{
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);
}
}
答案 0 :(得分:0)
您的问题是您没有标记输入字符串。如果不通过空格,逗号等分隔操作数,则无法从"3 4 +"
(不是)"34+"
告诉" "
(哪个是有效的RPN表达式)。前者是格式良好的表达式,后者应该导致错误。但是,在您的代码中,前者将被错误地评估(因为它尝试将{{1}}字符添加到堆栈并将其添加到事物中),后者将起作用,但不应该。