【问题标题】:Allowing user to write how many inputs does he want to put in允许用户写出他想输入多少个输入
【发布时间】:2021-03-15 10:05:55
【问题描述】:

几天前,我想参加一个编码挑战,但我真的很难完成一项基本任务,那就是输入。我的代码应该像这样工作:

用户应该输入数字T,然后他应该写T-times数字N,然后在下一行 N(随机)数字。输入和输出表可能如下所示。

T
N
(数字)

例如:
2 (T)
4(前N)
1 2 5 3(四个数字,因为第一个 N 是 4)
4(第二个N)
4 4 6 8(三个数字,因为第二个 N 是 4)

然后代码会将其处理为输出,但这不是那么成问题...

我尝试在 javascript(使用 node.js 和截止日期或提示)和 python 中对此进行编码,但我都失败了。在这里你可以看到我使用的代码:

const prompt = require("prompt");
let stepT = 0;
let stepN = 0;

prompt.start();
prompt.get(["T"], function (err, T) {
    reqN(T.T);
});

const reqN = T => {
    prompt.get(["N"], (err, N) => {
        console.log("I got N");
        let cisla = reqNumbers(T);
        if (++stepT < T) reqN(T);
        else stepT = 0;
    });
};

const reqNumbers = T => {
    prompt.get(["numbers"], (err, num) => {
        console.log("I got numbers");
        let cisla = num.numbers.split(" ");
        console.log(cisla);
        if (++stepN < T) reqNumbers(T);
        else stepN = 0;
        return cisla;
    });
};

(此代码使用 Javascript 和 node.js 提示)

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question('', (count) => {
    for (let i = 0; i < count; i++)
    {   rl.question('', (answer) => {
            console.log(answer);
        });
    };
  rl.close();
});

(在这段代码中,我尝试在 for 循环中使用 readline,以便我可以让用户说出他想要输入多少个输入。)

两者都失败了。虽然 readline 没有做任何事情,但 prompt-y 这样做: First, it wants T, then it wants N, that´s all alright. But then it should want numbers from me(as I wrote in the example) but it wants the second N and what is fascinating, when I should write the second N it looks like I can´t write one character at the time but only TWO! It looks like there are two prompts opened. And then it wants numbers where I again, can only write two characters at the time.

这不是我第一次遇到这个问题,所以这就是我决定在这里写的原因......如果有人可以提供帮助,我将非常感激。

【问题讨论】:

    标签: javascript node.js prompt readline


    【解决方案1】:

    获取用户输入的最简单方法是使用prompt-sync

    const prompt = require('prompt-sync')();
    
    let T = Number(prompt('Enter T'));
    
    for (let i = 0; i < T; i++) {
        let N = Number(prompt('Enter N'));
        let numbers = [];
        for (let j = 0; j < N; j++)
            numbers.push(Math.floor(Math.random() * 10));
        console.log(...numbers);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-02-08
      • 1970-01-01
      • 2015-10-15
      • 2014-11-12
      • 2019-07-30
      • 1970-01-01
      • 2012-02-21
      • 2017-08-30
      • 2013-05-22
      相关资源
      最近更新 更多