我想编写一个程序来运行使用反向波兰表示法的计算器,我遇到了一些问题,我在解释它们的代码中有评论,所以如果有人可以伸出援助之手,它会是不胜感激! 我知道它与尝试在栈中获取位置-1有关,但我似乎无法解决它。Postfix RPN计算器调试
import java.io.BufferedWriter;
import java.io.IOException;
public class Calculator {
ArrayStack<Integer> stack;
BufferedWriter out;
public Calculator(BufferedWriter out) {
this.out=out;
}
public void processLine(String line) throws IOException {
stack = new ArrayStack<>();
String [] s = line.split ("\\s+");
int operador1;
int operador2;
int x=0;
String operator;
if (s[0].charAt(0)!='-'){ /if a string starts with a "-" it should be interpreted as a comment/
if (isNumber(item)) {
int c = Integer.parseInt(item);
stack.push(c);
} else {
switch(item){
case "*": /multiplies the last two entries in stack/
operador1= stack.peek();
stack.pop();
operador2=stack.peek();
stack.pop();
stack.push(operador2*operador1);
break;
case "/": /divides the last two entries in stack/
operador1= stack.peek();
stack.pop();
operador2=stack.peek();
stack.pop();
stack.push(operador2/operador1);
break;
case "+": /sums last two entries in stack/
operador1= stack.peek();
stack.pop();
operador2=stack.peek();
stack.pop();
stack.push(operador2+operador1);
break;
case "-": /subtracts last two entries in stack/
operador1= stack.peek();
stack.pop();
operador2=stack.peek();
stack.pop();
stack.push(operador2-operador1);
break;
case "%": /divides last two entries in stack/
operador1=stack.peek();
stack.pop();
operador2=stack.peek();
stack.pop();
stack.push(operador2%operador1);
break;
case ".": /removes top of stack and writes in output file/
operador1=stack.peek(); /error here ArrayIndexOutOfBoundsException: -1/
stack.pop();
out.write(operador1);
out.newLine();
break;
case "@x": /removes top of stack and puts it in x/
x= stack.peek();
stack.pop();
break;
case "x": /puts x in the stack's top/
stack.push(x);
break;
case "dup": /repeats top of stack in stack/
operador1=stack.peek();
stack.push(operador1);
break;
case "swap": /swaps the last two entries/
operador1=stack.peek();
stack.pop();
operador2=stack.peek();
stack.pop();
stack.push(operador2);
stack.push(operador1);
break;
case "drop": /remove top of stack/
stack.pop();
}
}
}
}
System.out.println(" ");
}
public boolean isNumber (String x){
try{
int y=Integer.parseInt(x);
return true;
} catch (NumberFormatException e){
return false;
}
}
}