7.3 The offerMenuAsInt() action

The final action of the AdaptingMenu class is the offerMenuAsInt action. The design for this action is as follows.

The basis of this design is to show the menu, using showMenu(), and obtain a validated character choice, using getValidatedMenuChoice inherited from BasicMenu. The character obtained from the user is then converted into the appropriate integer value by searching through the optionKey array until the character entered by the user is located. The index of this location is then used as the value to be returned by the action.

Using the visualisation shown in Figure 7.3 and assuming that the user entered 'B', the search would locate 'B' in the optionKey array at location 2 and return this as the user's choice from the menu options. Thus it is always the manifest value of the option which is returned by this action, not the position which the option might occupy on the menu. The implementation of this design is as follows.

0034   public int offerMenuAsInt() { 
0035   
0036   char    responseAsChar;
0037   int     thisOne       = 0;
0038   boolean isNotFound    = true;
0039 
0040        showMenu();
0041        responseAsChar = getValidatedMenuChoice();
0042        
0043        while ( isNotFound) { 
0044           if ( optionKey[ thisOne] == responseAsChar) { 
0045               isNotFound  = false;
0046           } else {     
0047               thisOne++;
0048           } // End if.
0049        } // End while.
0050        return thisOne;
0051   } // End offerMenuAsInt.

The indefinite loop controlling the search of the optionKey array is controlled by a boolean variable called isNotFound in a similar way to the control of the loop in getValidatedMenuChoice, as described in the previous chapter. This action trusts the showMenu() action to make sure that the values of minimumOption and maximumOption and the optionKey array are set as specified above. Thus the value obtained by getValidatedMenuChoice() must be one of the values stored in the optionKey array and this guarantees that the loop in this action will terminate without attempting to access a value outside the range of the array.