Advertisement
mbah_bejo

Parser

Nov 15th, 2020
793
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.17 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. /**
  4.  * Class ini adalah bagian dari "World of Zuul".
  5.  * "World of Zuul" sangat simple, game adventure berbasis text.
  6.  *
  7.  * parser ini membaca input pengguna dan mencoba menerjemahkannya sebagai
  8.  * "Adventure" command. Setiap kali dipanggil Class membaca baris dari terminal dan
  9.  * mencoba untuk menerjemahkan baris tersebut sebagai 2 kata command. Class me-return command
  10.  * sebagai objek dari class Command.
  11.  *
  12.  * Parser memiliki sekumpulan kata command yang diketahui.
  13.  * Ia memeriksa input pengguna terhadap command yang diketahui,
  14.  * dan jika input bukan salah dari commands yang diketahui, maka
  15.  * me-return objek command yang ditandai sebagai perintah yang tidak diketahui.
  16.  *
  17.  * @author  thomasdwi.a
  18.  * @version 20201115
  19.  */
  20. public class Parser
  21. {
  22.     private CommandWords commands;  // holds all valid command words
  23.     private Scanner reader;         // source of command input
  24.  
  25.     /**
  26.      * Membuat parser untuk membaca terminal.
  27.      */
  28.     public Parser()
  29.     {
  30.         commands = new CommandWords();
  31.         reader = new Scanner(System.in);
  32.     }
  33.  
  34.     /**
  35.      * @return Command berikutnya dari pengguna.
  36.      */
  37.     public Command getCommand()
  38.     {
  39.         String inputLine;   // akan menampung baris input
  40.         String word1 = null;
  41.         String word2 = null;
  42.  
  43.         System.out.print("> ");     // print prompt
  44.  
  45.         inputLine = reader.nextLine();
  46.  
  47.         // Find up to two words on the line.
  48.         Scanner tokenizer = new Scanner(inputLine);
  49.         if(tokenizer.hasNext()) {
  50.             word1 = tokenizer.next();      // mendapat kata pertama
  51.             if(tokenizer.hasNext()) {
  52.                 word2 = tokenizer.next();      // mendapat kata kedua
  53.                 // note: kami hanya mengabaikan sisa baris input.
  54.             }
  55.         }
  56.  
  57.         // Sekarang periksa apakah kata ini dikenal. Jika demikian, buat command
  58.         // dengan itu. Jika tidak, buat command "null" (untuk command yang tidak diketahui).
  59.         if(commands.isCommand(word1)) {
  60.             return new Command(word1, word2);
  61.         }
  62.         else {
  63.             return new Command(null, word2);
  64.         }
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement