[英]Postfix RPN Calculator debugging
我正在尝试使用反向抛光符号来编写程序以运行计算器,但遇到了一些问题,代码中有注释说明了这些问题,因此,如果有人可以伸出援手,将不胜感激! 我知道这与尝试在堆栈中获得位置-1有关,但我似乎无法解决。
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;
}
}
}
在我看来,您的剪切和粘贴速度可能太快了。 您的代码中有些事情还不清楚。 很难确切猜出您需要什么帮助,但是如果您需要更好的帮助,则可能需要澄清以下几点:
您的括号数量不匹配。 我怀疑System.out.println(" ");
之前的那个System.out.println(" ");
是应该去的那个。
您无需遍历字符串数组,而只需查看一次即可。 看起来可疑。 更应如此,因为你创建一个新的ArrayStack
为每次调用processLine
这就不清楚,如果你打算处理一次只有一个令牌或一次。
您选择的注释语法似乎与否定运算符冲突。 我想如果您想一次处理所有令牌,这可能是可以的,因为不能先读一个运算符,但这不是为了简化编码和调试而对符号的最佳使用。
item
变量未在任何地方定义。
operator
变量不在任何地方使用。
您没有验证输入字符串,是否假设输入字符串将始终格式正确? 如果是这样,最好也发布失败的输入,因为有多个输入被设计为失败的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.