1.3-Object-Georienteerd-Programmeren

Option selection

Most of the classes we have created, in one shape or form, have represented actual real life things, such as people, cars and even airplanes. However, a lot of classes that are used during programming do not represent something tangible, but rather represent a concept, such as a list, queue, printer or even a menu.

Today you’ll create your own basic option selector. An option selector is a component that displays a list of items and allows you to select an item based on some kind of interaction (either by clicking on an element, typing it’s name, etc.). For now, let’s keep things simple and have you number all options of the list and allowing the user to enter a value after which the associated object is returned.

Make sure you implement the following methods:

To demonstrate the system, we’ll use a very simplistic Person class as the target to be selectable, but you can do many other things. The main purpose of the selector is that it is 1) reusable and 2) easy to standardize parts of your application.

The usage of the option selector looks like this:

public static void main(String[] args) {
    OptionSelector menu = new OptionSelector();

    menu.addOption(new Person("John"));
    menu.addOption(new Person("Jill"));
    menu.addOption(new Person("Joann"));
    menu.addOption(new Person("Nick"));
    menu.addOption(new Person("Bert"));
    menu.addOption(new Person("Ravi"));
    menu.addOption(new Person("Elton"));

    Person selectedPerson = menu.promptMenu();

    System.out.println("The person selected was: " + selectedPerson);

}

Note that we’ll not be bothered today by making this OptionSelector generic (e.g. take all types instead of just the Person class). We’ll leave that for a later course.

Obviously you’ll need to do some proper encapsulation, make sure you cannot enter illegal values!

Example

*************** Option selector ***************
1) John
2) Jill
3) Joann
4) Nick
5) Bert
6) Ravi
7) Elton

Please select a value: -10
Invalid value. Please try again: 25
Invalid value. Please try again: 6
The person selected was: Ravi