      1  import java.util.ArrayList;

      2  import java.util.Scanner;

      3

      4  /**

      5     A menu that is displayed on a console.

      6  */

      7  public class Menu

      8  {

      9     private ArrayList<String> options;

     10     private Scanner in;

     11

     12     /**

     13        Constructs a menu with no options.

     14     */

     15     public Menu()

     16     {

     17        options = new ArrayList<String>();

     18        in = new Scanner(System.in);

     19     }

     20

     21

     22     /**

     23        Adds an option to the end of this menu.

     24        @param option the option to add

     25     */

     26     public void addOption(String option)

     27     {

     28        options.add(option);

     29     }

     30

     31     /**

     32        Displays the menu, with options numbered starting with 1,

     33        and prompts the user for input. Repeats until a valid input

     34        is supplied.

     35        @return the number that the user supplied

     36     */

     37     public int getInput()

     38     {

     39        int input;

     40        do

     41        {

     42           for (int i = 0; i < options.size(); i++)

     43           {

     44              int choice = i + 1;

     45              System.out.println(choice + ") " + options.get(i));

     46           }

     47           input = in.nextInt();

     48        }

     49        while (input < 1 || input > options.size());

     50        return input;

     51     }

     52  }

     53

     54