J.4. Class Keypad

Class Keypad (Fig. J.3) represents the keypad of the ATM and is responsible for receiving all user input. Recall that we are simulating this hardware, so we use the computer's keyboard to approximate the keypad. We use method Console.ReadLine to obtain keyboard input from the user. A computer keyboard contains many keys not found on the ATM's keypad. We assume that the user presses only the keys on the computer keyboard that also appear on the keypadthe keys numbered 09 and the Enter key.

Figure J.3. Class Keypad represents the ATM's keypad.

1 // Keypad.cs 2 // Represents the keypad of the ATM. 3 using System; 4 5 public class Keypad 6 { 7 // return an integer value entered by user 8 public int GetInput() 9 { 10 return Convert.ToInt32( Console.ReadLine() ); 11 } // end method GetInput 12 } // end class Keypad

Method GetInput (lines 811) invokes Convert method ToInt32 to convert the input returned by Console.ReadLine (line 10) to an int value. [Note: Method ToInt32 can throw a FormatException if the user enters non-integer input. Because the real ATM's keypad permits only integer input, we simply assume that no exceptions will occur. See Chapter 12, Exception Handling, for information on catching and processing exceptions.] Recall that ReadLine obtains all the input used by the ATM. Class Keypad's GetInput method simply returns the integer input by the user. If a client of class Keypad requires input that satisfies some particular criteria (i.e., a number corresponding to a valid menu option), the client must perform the appropriate error checking.

Категории