Verification
Line: |
Input Line |
|
Type: |
Exercise |
You should have completed: |
Bad Data
|
This topic leads to: |
This is the end of the line.
|
Summary
When asking the user for input, not only is it important to get the right type of data (a number, string, or single letter), but also that that data be valid for the use to which we are about to put it. For example, we wish to calculate the square root of a number provided by the user.
Task
- Create a console application to calculate the square root of a number provided by the user. Hint: The Math library contains a function to calculate a square root.
- Run the program and enter -1
Note that the result is 'Not a number' or NaN
- Now modify the program so that the value the user entered is checked to see if it is valid (i.e. 0 or greater) before attempting the calculation. If the value is not valid, the program must ask the user again until they do enter a valid number.
- Run the program and enter -1 to check this validation takes place
Questions
-
How would you check that the number entered was in a certain range, say 100-1000?
- If the number was out of this range, how could you set it to the nearest valid number? Would it be wise to do so?
- How would you check that a string entered was the correct length, such as a 7 character SID?