AaronC AaronC - 7 months ago 9
Javascript Question

Leaving a for loop when input is successful

I was wondering how you leave a for loop if the input is successful, the user will have 3 attempts to enter a number above 0. Its working for them being unsuccessful but its still making me enter the value 3 times even if a correct number is inputted.

for (var attempts = 3; attempts--;) {
var input = window.prompt("Please enter a number");
if ( input < 0) {
document.write("Try Again");
}
}
document.write("Grand");

Answer

Here are the problems with your code:

  1. You have no else statement. If they don't enter the correct code it doesn't process anything else conditionally. It will always process the "Grand" output regardless of input.
  2. The condition of < 0 isn't what you want. If they enter 0 it would still pass the check and say "Try Again"
  3. The answer to your actual question, simply add a break in the (missing) else statement.

Try this:

<script>
for (var attempts = 1; attempts <= 3; attempts++) {
  var input = window.prompt("Please enter a number");
  if (input <= 0) {
    if (attempts == 3) {
       //this is the 3rd failure 
       document.write("You have failed 3 times!");
       break;
    } else {
       //this is for the 1st and second failures
       document.write("Try Again<br>");
    }
  } else {
    document.write("Grand");
    break;
  }
}
</script>