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 Q3(b)(i): improve an algorithm with a range check that rejects values less than zero: the same idea as your
if.
الصعوبة 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.
اضغط تشغيل لرؤية المخرجات هنا.