Skip to content
ExamSpine

Lesson 6.4 · Write it

Snack order

A whole programPython or Java10 tests, 7 of them hidden

On a phone? Put the lines in order instead

Write a program that reads a snack order and prints what it costs. When a line is not a whole number, the program says so and uses a fallback number instead of stopping.

  1. The first line is the number of sandwiches, at 4 dollars each. The second line is the number of drinks, at 2 dollars each.
  2. If the first line is not a whole number, print Sandwiches not clear, using 1 and count 1 sandwich.
  3. If the second line is not a whole number, print Drinks not clear, using 0 and count 0 drinks.
  4. Last, print Total: followed by the cost in dollars.
  5. A line that is a whole number is from 0 to 50, written with digits only. Any other line is a word, a decimal such as 2.5, or empty.

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 10 times: the 3 examples below, and 7 hidden ones that check the rules above. Only what it prints is checked.

  • both lines are whole numbers: 2 times 4 plus 3 times 2 (rules 1 and 4)

    You type

    1. typed: 2
    2. typed: 3

    It prints

    Total: 14
  • the sandwiches line is a word, so 1 sandwich is counted, and the drinks line is still used (rule 2)

    You type

    1. typed: two
    2. typed: 3

    It prints

    Sandwiches not clear, using 1
    Total: 10
  • the drinks line is a word, so 0 drinks are counted (rule 3)

    You type

    1. typed: 2
    2. typed: some

    It prints

    Drinks not clear, using 0
    Total: 8
solution.pySolution.java