fork download
  1. import java.io.*;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4.  
  5. interface Command {
  6. void execute() throws Exception;
  7. }
  8.  
  9. class RuntimeExecCommand implements Command {
  10. private final String command;
  11.  
  12. public RuntimeExecCommand(String command) {
  13. this.command = command;
  14. }
  15.  
  16. @Override
  17. public void execute() throws Exception {
  18. Runtime.getRuntime().exec(command);
  19. }
  20. }
  21.  
  22. class PrintCommand implements Command {
  23. private final String printString;
  24.  
  25. public PrintCommand(String printString) {
  26. this.printString = printString;
  27. }
  28.  
  29. @Override
  30. public void execute() throws Exception {
  31. System.out.println(printString);
  32. }
  33. }
  34.  
  35. class Jarvis {
  36.  
  37. private static final Map<String, Command> COMMANDS = new HashMap<String, Command>();
  38. static {
  39. COMMANDS.put("jarvis you there?", new PrintCommand("at your service sir"));
  40. COMMANDS.put("run command prompt", new RuntimeExecCommand("cmd.exe /c start"));
  41. COMMANDS.put("run notepad", new RuntimeExecCommand("notepad.exe"));
  42. // ...
  43. }
  44.  
  45. public static void main(String args[]) throws IOException {
  46. for (;;) {
  47. System.out.println("Command me: ");
  48. String line = br.readLine();
  49. if (line == null || line.isEmpty())
  50. break;
  51. Command command = COMMANDS.get(line);
  52. if (command != null) {
  53. try {
  54. command.execute();
  55. } catch (Exception e) {
  56. System.out.println("Failed to execute command because of:" + e);
  57. }
  58. } else {
  59. System.out.println("Unknown Command.");
  60. }
  61. }
  62. System.out.println("Goodbye.");
  63. }
  64. }
  65.  
Success #stdin #stdout 0.08s 380224KB
stdin
jarvis you there?
run notepad
stdout
Command me: 
at your service sir
Command me: 
Failed to execute command because of:java.io.IOException: Cannot run program "notepad.exe": error=2, No such file or directory
Command me: 
Goodbye.