package directory; import java.util.Scanner; /** An application that prompts the user for operations stack of persons * and performs these operations. * This contract must be provided by a stack implementation. * @author Jan Stelovsky, UH ICS AMI Lab */ public class StackUI { /** Constants that represent operations on stack. * As the push operation needs a string attribute, the constants * provide for setting and getting such attribute. */ enum Operation {push, pop, empty, list, quit; /** The string to store. */ private String string; /** Stores a string. * @param string to store */ public void setString (String string) {this.string = string;} /** Returns the stored string. * @return the stored string */ public String getString () {return string;} } /** The user's input from the console. */ private Scanner scanner = new Scanner (System.in); /** Prompt to the user displayed in the console. */ private static final String prompt = "push (+ name), pop (-), empty (?) or quit (!)>"; /** Creates and starts a new StackUI application. */ public StackUI () { BinarySearch search = new BinarySearch (); Stack stack = new StackAsArray (); // prompt the user for operation Operation operation = promptForOperation (prompt); while (operation != Operation.quit) { switch (operation) { case push: // search the database for the last name of the person entered Person person = search.binarySearch (Operation.push.name ().toLowerCase ()); if (person != null) {stack.push (person); } else {System.out.println ("there is no person whose last name starts with '" + string + "'");} break; case pop: System.out.println (stack.pop ()); break; case empty: System.out.println ("stack is" + (stack.empty () ? "" : "n't") + " empty"); break; case list: System.out.println (stack); break; } // prompt the user for operation operation = promptForOperation (prompt); } } /** Prompts the user and returns the operation requested possibly with a stored string. * @param prompt to display in the console * @return the operation incl. it's string argument */ private Operation promptForOperation (String prompt) { // prompt the user System.out.println (prompt); // read the user's entry from the console; strip surrounding whitespace String line = scanner.nextLine ().trim (); // determine operation based on the 1st character switch (line.charAt (0)) { case '+': // interpret the remainder of the line as string to search for Operation.push.setString (line.substring (1).trim ()); return Operation.push; case '-': return Operation.pop; case '?': return Operation.empty; case ':': return Operation.list; default: return Operation.quit; } } /** Creates and executes the StackUI application. * @param arguments no used */ public static void main (String [] arguments) { new StackUI (); } }