我正在尝试基于Shunting-yard算法构建我自己的表达式求值器。我很难将String
个对象添加到堆栈中。我的代码每次都跳过这些行,即使条件满足。有什么建议?我将operatorStack
声明为:
Stack operatorStack = new Stack();
我认为它与我的if语句有关。我已经使用Eclipse调试器对其进行了测试,当currentChar
变量显示为"("
时,它仍然会跳过推送到堆栈。
以下是有问题的摘录:
int count = 0;
String currentChar=new String();
//While loop to test for the conditions stated in the Shunting-yard algorithm.
while (count<=temp.length()) {
currentChar = temp.substring(count, count+1);
if(currentChar == "(")
operatorStack.push(currentChar);
if(expressionEval(currentChar) instanceof Integer)
outputQueue.offer((Integer)expressionEval(currentChar));
if(currentChar == "+" ||
currentChar == "-" ||
currentChar == "<" ||
currentChar == "?") {
while(operatorStack.peek() == "+" ||
operatorStack.peek() == "-" ||
operatorStack.peek() == "<" ||
operatorStack.peek() == "?") {
outputQueue.offer((Integer)operatorStack.peek());
operatorStack.pop();
}
operatorStack.push(currentChar);
}
答案 0 :(得分:2)
您正在使用&#34; ==&#34;来比较字符串。而不是&#34;等于&#34;。 从未满足比较条件。
另外你应该考虑使用&#34; char&#34;而不是&#34; String&#34;当我看一下单个字符时,使用myString.charAt(count)(例如)。
---这是考虑你在Java中尝试这个。