Untitled
unknown
javascript
4 years ago
1.6 kB
7
Indexable
<script type="text/javascript"> //we generate a random number from 0 to 100 using Math.floor and Math.random var number = Math.floor(Math.random() * 100); alert("A random number from 1 to 100 has been generated."); //count represents the number of attempts var count = 0; //flag represents if guess is correct or not var flag = 0; //we put the process of guessing in a while loop //the guess attempt is 5 times //we use prompt to take user input while(count < 5){ var guess = prompt("Enter guess # " +(count+1)+ " (0 to 100): "); //if guess is null, meaning the prompt was cancelled then we exit the loop and the program if(guess == null){ break; } //if guess is in between 0 to 100 then proceed to checking the number if(guess >= 0 && guess <= 100){ //we add to number of attempt count++; //we check if number is equal to guess //if it is then we change the flag to 1 //making the guess correct and break out of the loop using break if(guess == number){ flag = 1; break; //if not then we check if the guess is lower or higher than the number }else if(guess < number){ alert("That was too low."); }else if(guess > number){ alert("That was too high."); } //we also check if the number is valid or not }else { alert("Invalid number. Try again."); } } //if flag equal to 1 then we say congratulations to the user. Otherwise we say goodbye if(flag == 1){ alert("Congratulations! It took you " +count+ " number of attempt/s"); }else{ alert("Goodbye."); } </script>
Editor is loading...