Skip to content

Checkpoint: Validate a Duration

The Course
•
30 min study

The study planner will accept a duration typed by a person, and people type all sorts of things: nothing at all, a blank line, 0, later, or a number far too large. A program that answers all of these with one vague "invalid input" leaves the person guessing. In this checkpoint you read one line and give each kind of problem its own message, using Result twice: once for reading and once for parsing.

What you will use

  • read_line and its Result. Ok means a line was read, possibly an empty one. Keep the Err arm for a failed read.
  • trim and is_empty. End of input and a blank line both trim to empty text, so one check covers both.
  • parse::<u32>(). Its Err means the text is not a whole number that fits in a u32, which includes negative numbers and decimals.
  • A match guard. Ok(minutes) if minutes >= 1 && minutes <= 240 accepts only the allowed range; the next Ok(_) arm catches every other number.

Plan before you type

  1. Inside the Ok arm, bind let text = input.trim();.
  2. If text is empty, print Enter a duration and do nothing else.
  3. Otherwise match text.parse::<u32>() with three arms: in range, out of range, not a number.
  4. Write the in-range arm first, so the general Ok(_) arm cannot hide it.
  5. Run the six inputs listed below and compare each line of output.
Prove every branch runs

A branch you never ran is a branch you have not tested. Run the solution with each of these in the stdin box and write down the result before you look: nothing at all, a single space, 0, 240, 241 and later. Together they reach every message, and 0, 240 and 241 sit right on the edges of the range. If 240 is rejected, a < was written where <= belongs.

Mistakes worth checking for

  • A blank line prints Enter a whole number: the program parses before checking for empty text.
  • 45 is rejected as not a number: parse ran on input instead of the trimmed text, so it saw the newline.
  • 240 prints Use 1–240 minutes: the guard uses minutes < 240, which leaves out the upper boundary.
  • -5 prints Use 1–240 minutes: you parsed as a signed type such as i32. With u32, a negative number fails to parse, which is the message the task asks for.
  • Every number is accepted or every number is rejected: the unguarded Ok(_) arm comes before the guarded one.
Exercise

Your turn

Read one line from stdin. Print Enter a duration for blank input or end of input, Accepted: 45 minutes for the prefilled 45, Use 1–240 minutes for values outside the range, and Enter a whole number for invalid numbers. Keep the input-read error branch. Check 0, 240, 241 and later.

Your working space Rust
use std::io;

fn main() {
    let mut input = String::new();
    match io::stdin().read_line(&mut input) {
        Ok(_) => println!("Read: {}", input.trim()),
        Err(_) => println!("Could not read input"),
    }
}
45
Hint 1: the idea

Handle blank text first. For nonblank text, keep the type conversion separate from the range check.

Hint 2: a first step

In the Ok arm, bind the trimmed text and check whether it is empty before parsing.

Worked solution
Run the solution Rust
use std::io;

fn main() {
    let mut input = String::new();
    match io::stdin().read_line(&mut input) {
        Ok(_) => {
            let text = input.trim();
            if text.is_empty() {
                println!("Enter a duration");
            } else {
                match text.parse::<u32>() {
                    Ok(minutes) if minutes >= 1 && minutes <= 240 => {
                        println!("Accepted: {minutes} minutes");
                    }
                    Ok(_) => println!("Use 1–240 minutes"),
                    Err(_) => println!("Enter a whole number"),
                }
            }
        }
        Err(_) => println!("Could not read input"),
    }
}
45
Text
Accepted: 45 minutes

Each message tells the person which rule their input broke, so they know what to change. Notice that the range check never sees text: by the time the guard runs, minutes is already a u32. A huge value such as 99999999999 does not fit in a u32, so it gets Enter a whole number rather than the range message; decide whether that wording is good enough for your users. On Day 7 the planner runs these same checks for every line.

Was this article helpful?

Your response is saved on this device.