naufalphew

parser

Nov 16th, 2020
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.76 KB | None | 0 0
  1. /**
  2. * This class is part of the "World of Zuul" application.
  3. * "World of Zuul" is a very simple, text based adventure game.
  4. *
  5. * This parser reads user input and tries to interpret it as an "Adventure"
  6. * command. Every time it is called it reads a line from the terminal and
  7. * tries to interpret the line as a two word command. It returns the command
  8. * as an object of class Command.
  9. *
  10. * The parser has a set of known command words. It checks user input against
  11. * the known commands, and if the input is not one of the known commands, it
  12. * returns a command object that is marked as an unknown command.
  13. *
  14. * @author Naufal Fajar Imani
  15. * @version 1.0
  16. */
  17. import java.util.Scanner;
  18. public class Parser
  19. {
  20. private CommandWords commands; // holds all valid command words
  21. private Scanner reader; // source of command input
  22.  
  23. /**
  24. * Create a parser to read from the terminal window.
  25. */
  26. public Parser()
  27. {
  28. commands = new CommandWords();
  29. reader = new Scanner(System.in);
  30. }
  31.  
  32. /**
  33. * @return The next command from the user.
  34. */
  35. public Command getCommand()
  36. {
  37. String inputLine; // will hold the full input line
  38. String word1 = null;
  39. String word2 = null;
  40.  
  41. System.out.print("> "); // print prompt
  42.  
  43. inputLine = reader.nextLine();
  44.  
  45. // Find up to two words on the line.
  46. Scanner tokenizer = new Scanner(inputLine);
  47. if(tokenizer.hasNext()) {
  48. word1 = tokenizer.next(); // get first word
  49. if(tokenizer.hasNext()) {
  50. word2 = tokenizer.next(); // get second word
  51. // note: we just ignore the rest of the input line.
  52. }
  53. }
  54.  
  55. // Now check whether this word is known. If so, create a command
  56. // with it. If not, create a "null" command (for unknown command).
  57. if(commands.isCommand(word1)) {
  58. return new Command(word1, word2);
  59. }
  60. else {
  61. return new Command(null, word2);
  62. }
  63. }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment