Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package util;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Map.Entry;
- public class ConsoleUserInterface {
- // The map of the commands
- private final Map<String, CuiCommand> commandMap;
- private boolean exit;
- // The name of the cui
- private final String name;
- /**
- * @param name The name of the cui
- */
- public ConsoleUserInterface(String name) {
- this.name = name;
- this.commandMap = new HashMap<String, CuiCommand>();
- addCommand("help", new HelpCommand());
- addCommand("exit", new ExitCommand());
- }
- /**
- * Exits the main loop.
- */
- public void exit() {
- this.exit = true;
- }
- /**
- * Adds a command to this cui
- *
- * @param key
- * The key of the command, i.e. "help" for a HelpCommand.
- * @param cuiCommand
- * That's the actual CuiCommand.
- */
- public void addCommand(String key, CuiCommand cuiCommand) {
- commandMap.put(key.toLowerCase(), cuiCommand); // Puts the new command in the map
- }
- public void start() {
- String input;
- // These are the the different messages.
- String error = "There is no such command like \"[INPUT]\"";
- String helpMessage = "Type in \"help\" for help :P";
- System.out.println("-----------" + this.name + "-----------");
- System.out.println(helpMessage);
- // Now the programm enters the main loop.
- // You have to invoke exit() in order to exit this loop again.
- while (!exit) {
- input = Input.readString("Next action: ").toLowerCase(); // Reads the input
- System.out.println();
- // checks if there is a key of a command, which the user wants
- if (this.commandMap.containsKey(input)) {
- // if true, then execute the command!
- this.commandMap.get(input).execute();
- } else {
- // Print error message
- System.out.println(error.replaceAll("\\[INPUT\\]", input));
- System.out.println(helpMessage);
- }
- }
- System.exit(0);
- }
- private class ExitCommand implements CuiCommand{
- @Override
- public void execute() {
- exit();
- System.out.println("Exit the programm.");
- }
- @Override
- public String getDescription() {
- return "Exits the program.";
- }
- }
- private class HelpCommand implements CuiCommand{
- @Override
- public void execute() {
- // We use an iterator here.
- Iterator<Entry<String, CuiCommand>> commands = commandMap.entrySet().iterator();
- System.out.println("----Help----");
- while (commands.hasNext()) {
- // For each command entry print the key and the description!
- Map.Entry<String, CuiCommand> entry = commands.next();
- // Finally prints the information
- System.out.println(entry.getKey() + ": "
- + entry.getValue().getDescription());
- }
- System.out.println();
- }
- @Override
- public String getDescription() {
- return "Shows all commands.";
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement