Should I use a while or a do while loop if I want a prompt to loop till valid answer?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • hrstissiaopai
    New Member
    • Mar 2013
    • 27

    Should I use a while or a do while loop if I want a prompt to loop till valid answer?

    I have previously said that I am making a game that is text based with javascript, and I got a bunch of helpful replies, which told me to use a loop, but I do not know what loop exactly to use and how. Here is the context that I am using it in:
    Code:
    var turn=prompt("Where do you want to turn? Left or right?");
    if (turn=="left"){
    window.alert("You chose to turn left!");
    window.location="somepage1.html";
    }
    if (turn=="right"){
    window.alert("You chose to turn right!");
    window.location="somepage2.html";
    Please help. Thanks in advance.
  • divideby0
    New Member
    • May 2012
    • 131

    #2
    The type of loop depends on where you need/want to test. The while loop tests at the top, so the loop body may or may not be entered depending on the test condition. The do while tests at the bottom and will enter the loop body at least once. The for loop can behave either way depending on how it's initialized.

    With your code, maybe something like

    Code:
    var turn = prompt(...);
    
    while(test conditions are false)
    {
       turn = prompt(...);
    }
    
    // manipulate turn's value here
    Another thing is javascript treats LEFT, left, LEft, etc as different strings. To deal with that, you can use turn.toLowerCas e() or turn.toUpperCas e() in your test conditions.

    Comment

    Working...