Code:
using System;
using System.Collections;
namespace stackHeap {
//--- Application entry class.
class SelectionListExample {
public static void Main () {
Console.WriteLine ("SelectionList Examples. ");
SelectionList list = new SelectionList ();
list.Add ("February.", "June.", "July.", "October.", "November.");
//>>> POINT A <<<
int result = list.Display ();
Console.WriteLine ("You selected item {0}.", result);
Console.WriteLine ("=== end of program. ");
} // end Main method
} // end SelectionListExample class
//--- A class for displaying a list of options and returning the user's selection.
public class SelectionList {
private ArrayList items;
public SelectionList ()
{ this.items = new ArrayList (); }
//--- Add one or more list items.
public void Add (params String[] items) {
this.items.AddRange (items);
} // end Add method
//--- Display the list to the user, get a valid list item selection
//--- and return the number of the item selected.
//--- Returns 0 if list is exited with no selection.
public int Display () {
// Display list of items to the user.
Console.WriteLine ();
Console.WriteLine (" 0. No selection.");
for (int i=1; i<=items.Count; i++) {
Console.WriteLine (" {0}. {1}", i, (String)items[i-1]);
}
// Get a valid list selection.
int selection = 0;
bool ok = false;
while (!ok) try {
Console.Write (" Enter selection : ");
selection = Convert.ToInt32 (Console.ReadLine());
if (selection>=0 && selection<=items.Count)
ok = true; // Valid input selection made.
else
Console.WriteLine ("*** Invalid selection, try again. ");
} catch (Exception)
{ Console.WriteLine ("*** Invalid selection, try again. "); }
// End of input selection loop.
return selection;
} // end display method
} // end Selectionlist class
} // end namespace.
