我正在尝试编写一个程序来计算来自arrayList中元素的数学表达式。例如,["(", "3", "*", "2", ")"]等同于自(3*2)=6以来的答案6。
为此,我将元素压缩到两个堆栈中:operatorStack和valueStack。operatorStack接受括号和运算符,而valueStack只接受数字。
我的问题是,当我有这样一个arrayList时,["(", "(", "3", "*", "3", ")", "*", "(", "5", "*", "2", ")", ")"]是((3*3)*(5*2))的数学等价物,答案是10,而不是预期的90。
我不知道我的栈推/弹出的错误在哪里。
for(int i=0; i<tokenList.size(); i++) {
String indexString = tokenList.get(i);
//push to valueStack if num, else to operator Stack
if (isInteger(indexString)) {
valueStack.push(Integer.parseInt(indexString));
} else {
//if ) then calculate first
if(indexString.equals(")")) {
String opt = operatorStack.pop();
while(!opt.equals("(")) {
int valB = valueStack.pop();
int valA = valueStack.pop();
//check operators:
if(opt.equals("++")) {
tmp = tmp + 1;
}
if(opt.equals("--")) {
tmp = tmp - 1;
}
if(opt.equals("+")) {
tmp = valA + valB;
} else if (opt.equals("-")) {
tmp = valA - valB;
} else if (opt.equals("*")) {
tmp = valA*valB;
} else if (opt.equals("/")) {
tmp = valA/valB;
}
valueStack.push(tmp);
opt = operatorStack.pop();
i++;
}
} else {
operatorStack.push(indexString);
}
}发布于 2017-10-23 01:15:51
我建议i++语句中的问题(在while循环中):在结束括号(在我们的例子中是乘法符号).Try之后跳过下一个操作符来删除它。
https://stackoverflow.com/questions/46880509
复制相似问题