我是新來的JavaScript和有一些問題讓我的代碼,直到他們要求退出時不斷詢問用戶輸入。它運行一次,再次打印提示,然後退出。任何幫助將不勝感激。謝謝!我知道infix到postfix的實際轉換目前不起作用...Node.js Javascript程序正在退出而無需等待用戶的輸入
//RPN
var readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
var presedence = {'POW': 0, '*': 1, '/': 1, '%': 1, '+': 2, '-': 2};
var operators = ['P', '*', '/', '%', '+', '-'];
var digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
var convertInfix = function (infixQ) {
//PEMDAS
var opS = [];
var postfixQ = [];
var t;
while (infixQ.length != 0) {
t = infixQ.shift();
console.log(t)
console.log(typeof t)
if (digits.indexOf(t) > -1) {
console.log('push number')
postfixQ.push(t);
}
else if (opS.length === 0 || t == '(') {
console.log('push operator')
opS.push(t);
}
else if (t == ')') {
while (opS[0] != '(') {
opS.Push(t);
}
}
else {
while (opS.length != 0 && opS[0] != '(') {
if (presedence[t] > presedence[opS[0]]) {
break;
}
postfixQ.push(opS[0]);
opS.pop();
console.log
}
}
}
while (opS.length != 0) {
postfixQ.push(opS[0]);
opS.pop();
}
console.log(postfixQ)
};
var main = function() {
rl.question('Enter an infix expression or "quit" to exit the program:', (rawInfix) => {
if (rawInfix == 'quit') {
console.log('Exiting')
return;
} else {
var infixQ = [];
for (var i = 0; i < rawInfix.length; i++) {
if (digits.indexOf(raxInfix[i]) > -1 ||
operators.indexOf(rawInfix[i]) > -1 ||
rawInfix[i] == ' ') {
infixQ.push(rawInfix[i])
} else if (rawInfix[i] != 'W' || rawInfix[i] != 'O') {
console.log('Unexpected Character in input: ', rawInfix)
main()
}
}
postfixQ = convertInfix(infixQ)
main()
// evaluatePostFix(postfixQ)
}
rl.close();
});
}
main();
編輯:我用我的答案更好的文章替換了文章的鏈接。這一個更容易理解,你不必閱讀這麼多;-) – rweisse