← Back to Week 3 Hub
Workbook 3a — Exercise

Bedtime Stories

Read a text file line by line and print it back with line numbers  |  Workbook p.15-16

The Exercise

Create a Java app called bedtime-stories. In the provided DataFiles.zip you'll find three story files: goldilocks.txt, hansel_and_gretel.txt, and mary_had_a_little_lamb.txt. Place them in your project folder.

Ask the user which filename to read. Open the file with a BufferedReader, walk through it line by line, and print each line to the console — but add a line number before every line so the output looks like a numbered list.

Wrap the file work in a try/catch so a missing file gives a clean error message instead of a crash.

Example Run
Run 1 — Reading goldilocks.txt
Which story would you like to read? goldilocks.txt

1. Goldilocks and the Three Bears
2.
3. Once upon a time a girl named Goldilocks lived in
4. a house at the edge of the woods...
5.
6. One morning she went for a walk and came upon
7. a tiny cottage...
Run 2 — File not found
Which story would you like to read? cinderella.txt

Could not open that file. Check the name and try again.
Concepts You'll Use
Flow
Prompt for filename
Open FileReader + BufferedReader
Start line counter
Loop readLine() until null
Print "N. <line>"
Close the reader

Workbook 3a, p.15-16 — Exercise: Bedtime Stories

← Famous Quotes Payroll Calculator (Read) →