Search code examples
javascriptinputuser-inputreadline

while (line = readline())


I'm new to JavaScript and are trying to solve a problem. I shall only write in JavaScript and the instructions are telling me to use readline(), for example like this: while (line = readline())

But I cant get how this works and I cant find any information about this in JavaScript. I want to get a users input and then put that in a variable. But when I try "while (line = readline())" I can's se anything happen (like with propt, which is the only way I know)...

Thankful for your help!

Here is my code (which works if I use alert and prompt istead of print and readline):

var usersNumber;
while (usersNumber = readline()) {
if (1 <= usersNumber && usersNumber <= 1000000000)
{

var inputBinary = usersNumber.toString(2);

var binaryArray = [];

for (i = 0; i < inputBinary.length; i++) {
    binaryArray[i] = inputBinary.charAt(i);
};

binaryArray.reverse();

var stringBinaryFromArray = "";

for (i = 0; i < binaryArray.length; i++) {
    stringBinaryFromArray = stringBinaryFromArray + binaryArray[i];
}
var digit = parseInt(stringBinaryFromArray, 2);

print(digit);
}

}


Solution

  • readline() is not a standard Javascipt function. You can use prompt() instead

    while (usersNumber = prompt())
    

    You might need to change the input from a string to a number.

    while (usersNumber = Number(prompt()))
    

    On another note, there are built-in functions you can use instead of the loops you have. split() and join(). You can even do it all in 1 line.

    var stringBinaryFromArray = inputBinary.split('').reverse().join('');