역방향 폴란드어 표기법을 사용하여 계산기를 실행하는 프로그램을 코딩하려고하는데 일부 문제가 발생했습니다. 설명하는 코드에 주석이 있으므로 다른 사람이 도움의 손길을 빌려줄 수 있습니다. 대단히 감사합니다! 스택에서 위치 -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;
}
}
}