Advertisement
raffi_pratama

Untitled

Nov 16th, 2020
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.68 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3.  
  4.  
  5. /**
  6.  * Class Parser ini akan membaca inputan dari user dan menerjemahkannya sebagai
  7.  * "Adventure" command.
  8.  *
  9.  
  10.  * @author  M. Rayhan Raffi P.
  11.  
  12.  * @version 16-11-2020
  13.  
  14.  */
  15.  
  16. public class Parser
  17.  
  18. {
  19.  
  20.     private CommandWords commands;  // holds all valid command words
  21.  
  22.     private Scanner reader;         // source of command input
  23.  
  24.  
  25.  
  26.     /**
  27.  
  28.      * Create a parser to read from the terminal window.
  29.  
  30.      */
  31.  
  32.     public Parser()
  33.  
  34.     {
  35.  
  36.         commands = new CommandWords();
  37.  
  38.         reader = new Scanner(System.in);
  39.  
  40.     }
  41.  
  42.  
  43.  
  44.     /**
  45.  
  46.      * @return The next command from the user.
  47.  
  48.      */
  49.  
  50.     public Command getCommand()
  51.  
  52.     {
  53.  
  54.         String inputLine;   // will hold the full input line
  55.  
  56.         String word1 = null;
  57.  
  58.         String word2 = null;
  59.  
  60.  
  61.  
  62.         System.out.print("> ");     // print prompt
  63.  
  64.  
  65.  
  66.         inputLine = reader.nextLine();
  67.  
  68.  
  69.  
  70.         // Find up to two words on the line.
  71.  
  72.         Scanner tokenizer = new Scanner(inputLine);
  73.  
  74.         if(tokenizer.hasNext()) {
  75.  
  76.             word1 = tokenizer.next();      // get first word
  77.  
  78.             if(tokenizer.hasNext()) {
  79.  
  80.                 word2 = tokenizer.next();      // get second word
  81.  
  82.                 // note: we just ignore the rest of the input line.
  83.  
  84.             }
  85.  
  86.         }
  87.  
  88.  
  89.  
  90.         // Now check whether this word is known. If so, create a command
  91.  
  92.         // with it. If not, create a "null" command (for unknown command).
  93.  
  94.         if(commands.isCommand(word1)) {
  95.  
  96.             return new Command(word1, word2);
  97.  
  98.         }
  99.  
  100.         else {
  101.  
  102.             return new Command(null, word2);
  103.  
  104.         }
  105.  
  106.     }
  107.  
  108. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement