Skip to content
ExamSpine

Lesson 6.4 · Write it

Ask until it is a number

A whole programPython or Java9 tests, 6 of them hidden

On a phone? Put the lines in order instead

Write a program that reads how many laps a runner ran. It keeps reading lines until one of them is a whole number, instead of stopping at the first line that is not.

  1. For each line that is not a whole number, print Not a whole number: followed by the line, and read the next line.
  2. As soon as a line is a whole number, print Laps: followed by that number. Read no more lines after it.
  3. A line that is a whole number is from 0 to 200, written with digits only. Any other line is a word, a decimal such as 2.5, or empty.
  4. There is always a whole number in the end, but there may be any number of other lines before it.

In Python, convert each line with int and catch ValueError. In Java, convert it with Integer.parseInt and catch NumberFormatException.

Your program is run several times. Only what it prints is checked, and spaces at the end of a 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 9 times: the 3 examples below, and 6 hidden ones that check the rules above. Only what it prints is checked.

  • the first line is a whole number, so there is nothing to ask again (rule 2)

    You type

    1. typed: 12

    It prints

    Laps: 12
  • one word, then a whole number (rules 1 and 2)

    You type

    1. typed: ten
    2. typed: 10

    It prints

    Not a whole number: ten
    Laps: 10
  • two lines in a row that are not whole numbers (rules 1 and 4)

    You type

    1. typed: ten
    2. typed: 9.5
    3. typed: 9

    It prints

    Not a whole number: ten
    Not a whole number: 9.5
    Laps: 9
solution.pySolution.java