【发布时间】:2015-01-29 18:52:59
【问题描述】:
我目前正在用 Javascript 编写一个程序,其中用户输入一个中缀表示法表达式作为字符串,然后将其转换为后缀表示法。我无法将每个运算符推入堆栈。以下是与我的问题相关的两个主要代码部分。
var input = readLine();
postfixCalc(input);
//main function that converts an infix notation function to postfix
function postfixCalc (input) {
var operatorStack = new Stack();
print("length of input: " + input.length);//DEBUG
for (var i = 0; i < input.length; i++) {
if (isOperator(input[i])) {
operatorStack.push(input[i]);
print("Pushing to stack: " + input[i]);//DEBUG
} else {
print("Not an operator: " + input[i]);//DEBUG
}
print("This is what the input character is: " + input[i]);//DEBUG
}
}
//This function takes the current character being looked at in postfixCalc
//and returns true or false, depending on if the current character is
//a valid operator
function isOperator(y) {
//if y is a valid operator, return true.
if (y===("+" || "-" || "*" || "/" || "(" || ")")) {
print("What is being looked at: " + y);
return true;
} else {
return false;
}
}
仅比较此行中的第一个字符 if (y===("+" || "-" || "*" || "/" || "(" || ")")) { 从给定的字符串被推入堆栈。我用来测试的字符串是“3*5+6”。关于为什么会这样的任何想法?
【问题讨论】:
-
y===("+" || "-" || "*" || "/" || "(" || ")"))不是你想的那样。
标签: javascript postfix-notation infix-notation