我正在尝试从用户那里获取一个表达式并对其进行评估,但是我一直在遇到弹出方法错误,这些错误会导致arrayindexoutofboundsexceptions和null指针异常。我该如何解决,还有其他我所缺少的问题吗?谢谢
这是我的栈课
FileInfo oFile = new FileInfo(file);
string strType = oFile.Extension;
这里是评估者课程
public class MyStack<E> {
private E[] data;
private int top;
public MyStack() {
data = (E[]) (new Object[10]);
top = -1;
}
public void push(E item) {
top++;
data[top] = item;
}
public E peek() {
return data[top];
}
public E pop() {
top--;
return data[top + 1];
}
public boolean isEmpty() {
return top < 0;
}
}
这是主要班级
public class EvalPostfix {
private String post;
public EvalPostfix(String post) {
this.post = post;
}
public int eval() {
MyStack<Integer> stack = new MyStack<Integer>();
Scanner tokens = new Scanner(post);
int result = 0;
while (tokens.hasNext()) {
if (tokens.hasNextInt()) {
stack.push(tokens.nextInt());
} else {
int right = stack.pop();
int left = stack.pop();
if (tokens.equals("+")) {
result = left + right;
} else if (tokens.equals("-")) {
result = left - right;
} else if (tokens.equals("*")) {
result = left * right;
} else if (tokens.equals("/")) {
result = left / right;
}
stack.push(result);
}
}
return stack.pop();
}
}
答案 0 :(得分:0)
您将需要向MyStack类添加验证,以避免错误流。例如,如果堆栈已满,请勿尝试在push()方法内将项目添加到堆栈中。另外,在执行pop或peek()操作之前,您还必须检查Stack是否为空。看看下面的pop()操作内部的验证。
public E pop() {
if(isEmpty()){
// Handle the empty stack here (i.e : throw EmptyStackException)
}
top--;
return data[top + 1];
}