/* File: CommandLoop.java * Contains: A class for interactive command-loops * Author: Jeff Dalton * Created: February 1998 * Updated: Sat Sep 2 18:50:58 2000 by Jeff Dalton * Copyright: (c) 1998, AIAI, University of Edinburgh */ package ix.util; import java.util.*; import java.io.*; import ix.util.match.*; /** * */ public class CommandLoop implements Runnable { MatchTable commandTable; String prompt = "Command:"; String exit = "bye"; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintStream out = System.out; public CommandLoop(MatchTable commandTable) { this.commandTable = commandTable; } public CommandLoop(final Function1 eval) { this.commandTable = new MatchTable(); commandTable.addCase(new MatchCase() { public Object tryMatch(Object data) { return data; // always match (unless data == null) } public Object ifSelected(Object data, Object matchResult) { return eval.funcall(data); } }); } public void setPrompt(String prompt) { this.prompt = prompt; } public void setExitCommand(String exit) { this.exit = exit; } public void run() { out.println("Type \"" + exit + "\" to exit.\n"); for (;;) { try { String command = ask(prompt); if (command.equals(exit)) break; out.println(commandTable.match(command)); out.println(""); } catch (Exception e) { Debug.noteException(e); } } System.out.println("\nBye!\n"); } protected String ask(String prompt) throws IOException { out.print(prompt + " "); out.flush(); return in.readLine(); } }