Java · Beginner level

Beginner level · Module 5: Console Application Project in Java · Lesson 2 of 3

Building a Menu-Driven Program

Implement the plan in stages: data classes first, then a menu loop that calls their methods.

In this lesson you will

  • Build and test data classes before the user interface
  • Write a do-while menu loop that dispatches to methods

Key concepts

incremental developmentmenu loopswitch dispatchseparation of concerns

The lesson

Build the data classes first and test them from a short main method with fixed values. When Sale and SalesBook work, the menu only has to call them, and any bug is easier to locate.

A typical menu is a do-while loop: print the options, read a choice, use a switch to call the right method, and repeat until the user chooses Exit. Keep each case short — one or two method calls.

Run the program after every small change. If something breaks, you know it was the last change, which makes finding the cause quick.

Step by step

  1. Implement Sale and SalesBook and test them with fixed data.
  2. Write the menu loop with an Exit option.
  3. Connect each menu option to a SalesBook method.
  4. Run the program after each option is added.

Practice activity

Implement the add, list and total options of the Shop Sales Recorder and demonstrate them with five test sales.

Expected result: The three options work with the test data, and totals match a hand calculation.

Check your understanding

  1. Why test data classes before building the menu?

    Show answer

    Bugs are easier to find when each part is tested on its own first.

  2. Which loop suits a menu that must be shown at least once?

    Show answer

    A do-while loop.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.