Advertisement
mnaufaldillah

Parser Tugas 6

Nov 24th, 2020
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.26 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3. import java.util.StringTokenizer;
  4. /**
  5.  * This parser reads user input and tries to interpret
  6.  * it as an "Adventure" command. Every time it is called it reads a line
  7.  * from the terminal and tries to interpret the line as a two word command.
  8.  * It returns the command as an object of class Command.
  9.  *
  10.  * The parser has a set of known command words. It
  11.  * checks user input against the known commands, and if the input is not one of
  12.  * the known commands, it returns a command object that is marked as an
  13.  * unknown command.
  14.  *
  15.  * @author Muhammad Naufaldillah
  16.  * @version 24 Novemebr 2020
  17.  */
  18. public class Parser
  19. {
  20.     private CommandWords commands; // holds all valid command words
  21.    
  22.     public Parser()
  23.     {
  24.         commands = new CommandWords();
  25.     }
  26.    
  27.     public Command getCommand()
  28.     {
  29.         String inputLine = ""; // will hold the full line
  30.         String word1;
  31.         String word2;
  32.        
  33.         System.out.print("> "); // print prompt
  34.        
  35.         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  36.        
  37.         try
  38.         {
  39.             inputLine = reader.readLine();
  40.         }
  41.         catch(java.io.IOException exc)
  42.         {
  43.             System.out.println("There was an error during reading: " + exc.getMessage());
  44.         }
  45.        
  46.         StringTokenizer tokenizer = new StringTokenizer(inputLine);
  47.        
  48.         if(tokenizer.hasMoreTokens())
  49.         {
  50.             word1 = tokenizer.nextToken(); // get first word
  51.         }
  52.         else
  53.         {
  54.             word1 = null;
  55.         }
  56.        
  57.         if(tokenizer.hasMoreTokens())
  58.         {
  59.             word2 = tokenizer.nextToken(); // get second word word
  60.         }
  61.         else
  62.         {
  63.             word2 = null;
  64.         }
  65.        
  66.         // note: we just ignore the rest of the input line.
  67.        
  68.         // Now check whether this word is known. If so, create a command
  69.         // with it. If not, create a "null" command (for unknown command).
  70.        
  71.         if(commands.isCommand(word1))
  72.         {
  73.             return new Command(word1, word2);
  74.         }
  75.         else
  76.         {
  77.             return new Command(null, word2);
  78.         }
  79.     }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement