Lesson 40: Check the input
Stop bad data
- A machine that gets a silly value can break: a speed of 500, or a door code with a letter in it.
- Validation is an automatic check that the data is sensible before the program uses it.
- Then you test the check with good and bad data.
Words for this lesson
| Word | Meaning |
|---|---|
| range check | the value is between a lowest and a highest value |
| length check | the data has the right number of characters |
| type check | the data is the right kind, for example only digits |
| test data | values you type to see if the program works |
Kinds of test data (range 1 to 100)
| Kind | Example | Expected |
|---|---|---|
| normal | 25 | accepted |
| abnormal | 125 | rejected |
| extreme | 1, 100 | accepted |
| boundary | 0 and 1; 100 and 101 | first rejected, then accepted (and the other way at the top) |
Read a number
void setup() {
Serial.begin(9600);
String typed = "42";
int n = typed.toInt();
Serial.println(n + 1);
}
void loop() {
}
- The Monitor shows 43:
toInt()turns the text "42" into the number 42.
In the exam
- 0478/23/O/N/24 Q7: a program needs a value from 1 to 100; identify three types of test data with an example and the expected outcome. Mark scheme: normal (e.g. 25, accepted), extreme (1 or 100, accepted), abnormal (e.g. 125, rejected), boundary (1 and 0, or 100 and 101: one accepted, one rejected). Your first program is tested with all four kinds.
- 0478/22/F/M/24 Q5(b)(i): improve an algorithm with a range check that rejects values less than zero: the same idea as your
if. - 0478/22/F/M/25 Q4(b)(ii): write an algorithm that makes sure the input is an integer. Mark scheme: a condition-controlled loop; input and re-input of the value; the loop condition tests the input; a suitable error message; the loop ends when the input is valid. Your third program does this for a range check.
רמת קושי 3/5 · 200 מטבעות + בונוס קטן בהשלמה הראשונה היום
A machine needs a speed from 1 to 100, both included. Type a number into the Serial Monitor. Print Speed , the number and : accepted if it is in the range or : rejected if not, for example Speed 50: accepted. Check uses normal, boundary and wrong values: 50, 0, 1, 100 and 101.
לחץ על הרץ כדי לראות את התוצא כאן.
רמת קושי 4/5 · 280 מטבעות + בונוס קטן בהשלמה הראשונה היום
A door code must be exactly 4 characters long (a length check) and every character must be a digit 0 to 9 (a type check). Type a code. Print the code, then : wrong length, : digits only או : valid, for example 12a4: digits only. Do the length check first.
לחץ על הרץ כדי לראות את התוצא כאן.
רמת קושי 4/5 · 280 מטבעות + בונוס קטן בהשלמה הראשונה היום
A real program does not stop at bad data: it asks again until the input is valid. Read a speed with readNumber(). While it is out of the range 1 to 100, print Error: 1 to 100 only and read again. When it is valid, print Speed set to and the number. Check types 150, then 0, then 75.
לחץ על הרץ כדי לראות את התוצא כאן.