Skip to content
ExamSpine

Lesson 6.8 · Write it

Number the lines of a poem

A whole programPython or Java7 tests, 5 of them hidden

On a phone? Put the lines in order instead

Write a program that reads the file poem.txt and prints every line of it with its line number in front, then how many lines there were.

  1. For each line, in order, print the line number, then : , then the line exactly as it is in the file. The first line is number 1.
  2. Some lines start with spaces, to indent them. Keep those spaces.
  3. An empty line is still a line. It gets a number like the others.
  4. After the last line, print Lines: followed by the number of lines. A file with nothing in it has 0 lines.
  5. The last line may or may not end with a line end.

Your program is run several times, each time in a folder that holds only the files shown for that run. Spaces at the end of a printed line are ignored.

Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.

Examples

Your program is run 7 times: the 2 examples below, and 5 hidden ones that check the rules above. Only what it prints is checked. Each run starts in an empty folder that holds only the files shown for it.

  • two lines, numbered from 1, then the count (rules 1 and 4)

    You type

    Nothing

    It prints

    1: Rain on the roof
    2: and on the road
    Lines: 2

    Files in its folder

    poem.txt
    Rain on the roof
    and on the road
  • an indented line keeps its spaces (rule 2)

    You type

    Nothing

    It prints

    1: The tide
    2:   comes in
    3: slowly
    Lines: 3

    Files in its folder

    poem.txt
    The tide
      comes in
    slowly
solution.pySolution.java

Report a problem with this page