我使用堆栈和后缀表示法做计算器,我想向你们寻求帮助。 我收到了IndexOutBoundsException错误,我无法弄清楚为什么以及是否有人可以帮助我修复代码中的错误,这真的是一种错误!
编辑:修复第一个错误
public class Calculator {
String operator;
BufferedWriter out;
public Calculator(BufferedWriter out) {
this.out=out;
}
public void processLine( String line ) throws IOException {
ArrayStack<Integer> stack = new ArrayStack<Integer>() {
};
String [] s = line.split ("\\s+?");
int operand1;
int operand2;
int x=0;
if ((s[0].charAt(0))!='-')
for (String item : s) {
if (isNumber(item)) {
int c = Integer.parseInt(item);
stack.push(c);
} else {
operator = item;
}
switch(operator){
case "*":
operador1= stack.peek(); //IndexOutOfBounds here ///is this peeking, storing and popping thing good?
stack.pop();
operador2=stack.peek();
stack.pop();
stack.push(operand2*operand1);
continue;
case "/":
operand1= stack.peek();
stack.pop();
operand2=stack.peek();
stack.pop();
stack.push(operand2/operand1);
continue;
case "+":
operand1= stack.peek();
stack.pop();
operand2=stack.peek();
stack.pop();
stack.push(operand2+operand1);
continue;
case "-":
operand1= stack.peek();
stack.pop();
operand2=stack.peek();
stack.pop();
stack.push(operand2-operand1);
continue;
case "%":
operand1=stack.peek();
stack.pop();
operand2=stack.peek();
stack.pop();
stack.push(operand2%operand1);
case ".":
operand1=stack.peek();
stack.pop();
out.write(operand1);
continue;
case "@x":
x= stack.peek();
stack.pop();
continue;
case "x":
stack.push(x);
case "dup":
operand=stack.peek();
stack.push(operand1);
}
}
out.write(stack.toString());
}
public boolean isNumber (String x){
try{
int y=Integer.parseInt(x);
return true;
} catch (NumberFormatException e){
return false;
}
}
}