js实现Scanner

JavaScript 实现类似 Java Scanner 的功能
JavaScript 没有内置的 Scanner 类,但可以通过以下方式模拟类似功能:

使用浏览器控制台输入
function Scanner() {
this.nextLine = function() {
return prompt("Enter input:");
};
this.nextInt = function() {
return parseInt(prompt("Enter integer:"));
};
this.nextFloat = function() {
return parseFloat(prompt("Enter float:"));
};
}
const scanner = new Scanner();
const name = scanner.nextLine();
const age = scanner.nextInt();
使用 Node.js 的 readline 模块
const readline = require('readline');
function Scanner() {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
this.nextLine = function() {
return new Promise(resolve => {
rl.question('', answer => {
resolve(answer);
});
});
};
this.nextInt = async function() {
const input = await this.nextLine();
return parseInt(input);
};
this.close = function() {
rl.close();
};
}
(async function() {
const scanner = new Scanner();
console.log("Enter your name:");
const name = await scanner.nextLine();
console.log("Enter your age:");
const age = await scanner.nextInt();
scanner.close();
})();
处理字符串输入
如果需要从字符串中解析数据:
function Scanner(input) {
this.input = input.trim().split(/\s+/);
this.index = 0;
this.hasNext = function() {
return this.index < this.input.length;
};
this.next = function() {
return this.input[this.index++];
};
this.nextInt = function() {
return parseInt(this.next());
};
this.nextFloat = function() {
return parseFloat(this.next());
};
}
const scanner = new Scanner("John 25 175.5");
const name = scanner.next();
const age = scanner.nextInt();
const height = scanner.nextFloat();
注意事项
浏览器环境中的 prompt() 会阻塞 UI 线程 Node.js 版本需要使用异步/await 处理输入 字符串解析版本是同步的,适合处理预定义的输入 可以根据需要扩展更多方法如 nextDouble(), nextBoolean() 等






