我试图从用户那里获取一个表达式并对其进行评估,但我不断收到导致 arrayindexoutofboundsexceptions 和空指针异常的 pop 方法错误。我该如何解决这个问题,是否存在我遗漏的其他问题?谢谢
这是我的堆栈类
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();
}
}
这是主要课程
public class Prog4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter postfix expression: ");
String post = input.nextLine();
EvalPostfix ev = new EvalPostfix(post);
int result = ev.eval();
}
}