Reputation: 1565
I am trying to convert a C# snippet for a simple while loop to a JavaScript solution. The C# code asks for a input, prints the output, and as long as the input is not 0, continues the question.
For the JavaScript solution, I am using VS Code and the integrated terminal for the JS output using node. As I understand, when using node and the readline method, I can't use while loops? But resort to if and switch case?
This is my C# code:
public void WriteNumbers(int i)
{
while(i != 0)
{
PrintWriteNumbers();
break;
}
}
public void PrintWriteNumbers()
{
Console.WriteLine("Provide a number: ");
WriteNumbers(int.Parse(Console.ReadLine()));
}
Can I get this kind of behavior in the terminal with JavaScript or create a html page?
I started to use a html output for my JavaScript, this is code, but it is incomplete:
<h2>JavaScript While Loop</h2>
<p id="demo"></p>
<script>
let text = ""
let num
while (num !== 0) {
num = parseInt(prompt("write a number"))
text += "<br>The number is " + num
break
}
document.getElementById("demo").innerHTML = text
</script>
It does take in a number and prints it to the screen. What I want to actually do is to print the output to the p tag, and if the input is not 0, initiate the prompt again for a new input, and exit the prompt when it is 0.
Upvotes: 1
Views: 1072
Reputation: 5054
Your while loop should be written like this,
while (num !== 0) {
num = parseInt(prompt("write a number"))
if(num === 0) break;
text += "<br>The number is " + num
}
Upvotes: 2