Here’s an example of how you would prompt someone for information using the prompt function.
var aNumber = prompt("Please guess a number between 1 and 100");
This will show a dialog box on the screen allowing the user to enter some input. The result of what the user types in will (in this case) be stored in the variable aNumber.
The program should first randomly pick a number between 1 and 100 and then prompt the user to guess the number. It should also show the user how many guesses they have left:
When you guess a number, the application should do some validation on the input. It should:
- Validate that the inputted value is indeed a number (please see appendix for an explanation of how to do this)
- Validate that the inputted value is between
100(inclusive). This means that the number
0is an invalid input, but the value
1is valid. Also the value
101would be invalid, but the number
100would be valid.
If the value entered into the prompt is invalid, then you should prompt them again asking to input a valid number like so:
Once the inputted value is deemed valid, the application should compare your guessed number to the one originally picked.
If your number is larger, then the program will alert you with a message saying “
You need to guess a smaller number.”
If your number is smaller, then the program will alert you with a message saying “
You need to guess a larger number.”
And if you are able to guess the number, then the program will say “
Congrats! You got it! My number was: [randomly generated number]”
Note: be sure to replace the [randomly generated number] placeholder with the actual number that was chosen by the computer at the beginning.
If after 6 attempts the user was NOT able to guess the number correctly, you should display an alert like so:
Note: be sure to show the actual number that was randomly generated by the program, the number 21 displayed above was just the number that was picked when I ran my program.
Validating that a value is a number
In order to validate that a value is indeed numeric, you can use a function called isNaN(aVariable). This function takes a single parameter. This parameter will be checked by the function to see if it is a number or not.
If the variable is a number, it will return false. If the variable is NOT a number, it will return true.
isNaN("test") returns true
isNaN(10) returns false