This checkpoint is the input side of the reading log in miniature. Each line of standard input should be a duration in whole minutes, and the program must accept exactly the values from 1 to 240 and reject everything else without stopping. The supplied input is chosen with care: it holds both boundaries, the values just outside them, and a line that is not a number at all. A program that handles those five lines correctly is very likely to handle any others.
What you will use
- A scanner loop.
bufio.NewScanner(os.Stdin)andfor scanner.Scan()visit each line, andscanner.Text()gives its text. - Trimming.
strings.TrimSpaceremoves stray spaces before conversion, becausestrconv.Atoirejects them. - Conversion with an error check.
strconv.Atoireturns a number and an error; a non-nilerror means the line was not a whole number. - A range check. A converted number must be at least 1 and at most 240.
continue. After printingInvalid, move on to the next line instead of stopping.- A final
scanner.Err()check after the loop ends.
Plan before you type
- Import the five packages you need:
bufio,fmt,os,strconvandstrings. - Create the scanner and start the loop.
- Trim the line and convert it, keeping both the number and the error.
- If the conversion failed or the number is outside the range, print
Invalidand continue. - Otherwise print the number.
- After the loop, check
scanner.Err().
Before running, write the five expected output lines next to the five input lines. Then add your own test lines to the stdin box, such as 12 with spaces or an empty line, and predict them too.
One condition or two?
You can combine the checks into one condition with ||, because Go stops evaluating as soon as one part is true. If the conversion fails, the range tests never run. Separate if statements work just as well, and they let you print a different message for each problem, which the full reading log will do.
Mistakes worth checking for
240printsInvalid: the upper check uses>=instead of>.0is printed as a valid duration: the lower check uses< 0instead of< 1.- The program stops after the first bad line: a
returnorbreakwas used wherecontinuebelongs. laterprints0: the error fromAtoiwas ignored, so the failed conversion's zero value was printed.- The compiler reports
"strings" imported and not used, orundefined: strings: the import list does not match the code.
Your turn
Read each input line as a duration. Print whole numbers from 1 through 240 inclusive. Print Invalid for any other line, then continue. Check scanner.Err() at the end.
package main
func main() {
// Build your solution here.
}Hint 1: the idea
Test conversion and both ends of the range before using the number.
Hint 2: a first step
Trim each line before passing it to strconv.Atoi.
Worked solution
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
minutes, err := strconv.Atoi(strings.TrimSpace(scanner.Text()))
if err != nil || minutes < 1 || minutes > 240 {
fmt.Println("Invalid")
continue
}
fmt.Println(minutes)
}
if err := scanner.Err(); err != nil {
fmt.Println("Input error:", err)
}
}1
Invalid
240
Invalid
InvalidThe supplied input tests both edges and the values just outside them: 1 and 240 pass, 0 and 241 fail, and later fails conversion.
Before Day 6
Check that you can do each of these without looking back:
- Write the scanner loop from memory, including the error check after it.
- Say what
strings.Cutreturns for a line with no comma. - Explain why converting text and checking its range are two separate steps.
Day 6 moves these checks into functions of your own. A function will return a value and an error, and a table of test cases will prove that it accepts and rejects exactly what it should.
Completion is saved in this browser only. It does not measure mastery.