Advertisement
lamaulfarid

Parser

Nov 19th, 2020
295
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.13 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 Ahmad Lamaul Farid
  15. * @version 12 November 2020
  16. */
  17.  
  18. import java.util.Scanner;
  19. public class Parser
  20. {
  21.     private CommandWords commands; // holds all valid command words
  22.     private Scanner reader; // source of command input
  23.      
  24.     /**
  25.     * Create a parser to read from the terminal window.
  26.     */
  27.     public Parser()
  28.     {
  29.         commands = new CommandWords();
  30.         reader = new Scanner(System.in);
  31.     }
  32.      
  33.     /**
  34.     * @return The next command from the user.
  35.     */
  36.     public Command getCommand()
  37.     {
  38.         String inputLine; // will hold the full input line
  39.         String word1 = null;
  40.         String word2 = null;
  41.          
  42.         System.out.print("> "); // print prompt
  43.          
  44.         inputLine = reader.nextLine();
  45.          
  46.         // Find up to two words on the line.
  47.         Scanner tokenizer = new Scanner(inputLine);
  48.         if(tokenizer.hasNext())
  49.         {
  50.             word1 = tokenizer.next(); // get first word
  51.             if(tokenizer.hasNext())
  52.             {
  53.                 word2 = tokenizer.next(); // get second word
  54.                 // note: we just ignore the rest of the input line.
  55.             }
  56.         }
  57.          
  58.         // Now check whether this word is known. If so, create a command
  59.         // with it. If not, create a "null" command (for unknown command).
  60.         if(commands.isCommand(word1))
  61.         {
  62.             return new Command(word1, word2);
  63.         }
  64.         else
  65.         {
  66.             return new Command(null, word2);
  67.         }
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement