Hey, I am working on a course and it has set me a small challenge to make a script where people have to guess a random number and I can do that fine but the next part telsl me to add something to only allow users 3 attepts to guess it. Can someone please show me where I am going wrong please function whileTest() { var number = 5; var answer = 0; var attempt = "i"; while (answer < number) { answer = prompt("Please guess a random number between 1 and 10", ""); } if (answer == 5) { alert("Well done, you guessed the correct number!"); } else if (attempt == 3) { alert("Sorry, you were not able to guess the random number"); } else { attempt = (i++); } } Code (markup): Thanks in advance!
I think that the crux of your problem is that you've only got one statement inside your while loop. You probably want to toss the if / else if / else clauses INSIDE the while loop so that they are part of the while loop. You will find the Firebug addon for Firefox to be an indispensable tool when programming JavaScript.
function whileTest() { var number = 5; var answer = 0; var attempt = "i"; while (answer < number) { answer = prompt("Please guess a random number between 1 and 10", ""); } if (answer == 5) { alert("Well done, you guessed the correct number!"); } else if (attempt == 3) { alert("Sorry, you were not able to guess the random number"); } else { attempt = (i++); } } I don't understand, in this code, if you entered 6 it would just end, attempt would equal to 1. function whileTest() { var number = 5; var answer = 0; var attempt = 1; var max_attempt = 3; while (attempt <= max_attempt) { answer = prompt("Please guess a random number between 1 and 10", ""); if (answer == 5) { alert("Well done, you guessed the correct number!"); break; } else { alert("Sorry, only " + max_attempt - attempt + " more chance to guess the number."); attempt++; } } if(attempt > max_attempt){ alert("Sorry, you were not able to guess the random number."); } } That's off the top of my head, might not be 100% right. I can't check it atm. I think it should say Sorry, only 2 more chance to quess the number. Sorry, only 1 more chance to quess the number. Sorry, only 0 more chance to quess the number. Sorry, you were not able to guess the random number. Of course, the "0 more chance" doesn't make sense. Anyway, if they get it right it should just say Well done, you guessed the correct number!