/* Java application whose purpose is to test instances of the KeyPadLock1Q * class. * @version October 2019. * @author R. McCloskey * * If there is a command line argument, it provides the name of the file * containing the input data. Otherwise, input (for which prompts are * displayed) comes from standard input (i.e., the keyboard). * Input data is to include the lock's secret code (a sequence of decimal * digits) and a sequence of one-character command codes, each of which * (except for the quit command) corresponds to a key press on the lock's * keypad. * * For each command specified, the program reports that it is being * performed, the relevant method is applied to the lock and, afterwards, * the state (OPEN or CLOSED) of the KeyPadLock object is reported. * * The commands are as follows: * * q : quit (i.e., terminate program) * o : press OPEN key on the lock's keypad * c : press CLOSE key on the lock's keypad * 0 : enter 0 on the lock's keypad * 1 : enter 1 on the lock's keypad * . * . * 9 : enter 9 on the lock's keypad */ import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; public class KPL1Q_Tester { private static Scanner input; public static void main(String[] args) throws FileNotFoundException { // Establish the Scanner as reading either from the file whose name // was provided as the command line argument or, if there is no such // argument, from the keyboard. if (args.length != 0) { input = new Scanner(new File(args[0])); } else { input = new Scanner(System.in); } System.out.println("Creating a new KeyPadLock1Q object ... "); System.out.print("Enter secret code: "); String codeStr = input.next(); input.nextLine(); if (args.length != 0) { System.out.println(codeStr); } int[] code = digitStrToIntAry(codeStr); KeyPadLock kpl = new KeyPadLock1Q(code); System.out.println("A keypad lock with code " + codeStr + " has been created."); KeyPadLockTester.processCommands(kpl, input); System.out.println("Goodbye."); } /* Given a String composed of digit characters (in the range '0'..'9'), ** returns an array of integers containing the digits. ** Example: Given "56023", the returned array will be [5, 6, 0, 2, 3]. ** If any character in the given String is not a digit character, an ** IllegalArgumentException is thrown. */ private static int[] digitStrToIntAry(String codeStr) { int[] result = new int[codeStr.length()]; for (int i=0; i != result.length; i = i+1) { char ch = codeStr.charAt(i); if (Character.isDigit(ch)) { result[i] = charToDig(ch); } else { throw new IllegalArgumentException(ch + " is not a digit char."); } } return result; } /* pre: c is in the range '0'..'9' ** post: value returned is the integer value corresponding to c. ** E.g., if c is (the char) '4', value returned will be (the int) 4. */ private static int charToDig(char c) { return c - '0'; } }