-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParser.java
executable file
·86 lines (73 loc) · 2.46 KB
/
Parser.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
/**
* This class is the main class of the "Queen saving" Game`
*
* This parser reads user input and tries to interpret it as an "Adventure"
* command. Every time it is called it reads a line from the terminal and
* tries to interpret the line as a two word command. It returns the command
* as an object of class Command.
*
* The parser has a set of known command words. It checks user input against
* the known commands, and if the input is not one of the known commands, it
* returns a command object that is marked as an unknown command.
*
* @author Michael Kolling and David J. Barnes and 121880(Long Yu)
* @version 1.0 (Nov 2013)
*/
class Parser
{
private CommandWords commands; // holds all valid command words
/**
* Constructor of the Parser
*/
public Parser()
{
commands = new CommandWords();
}
/**
* Get the command of what player typed
* resolve the command and create the object of Command
* @return object of Command class
*/
public Command getCommand()
{
String inputLine = ""; // will hold the full input line
String word1;
String word2;
System.out.print("> "); // print prompt
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
try {
inputLine = reader.readLine();
}
catch(java.io.IOException exc) {
System.out.println ("There was an error during reading: "
+ exc.getMessage());
}
StringTokenizer tokenizer = new StringTokenizer(inputLine);
if(tokenizer.hasMoreTokens())
word1 = tokenizer.nextToken(); // get first word
else
word1 = null;
if(tokenizer.hasMoreTokens())
word2 = tokenizer.nextToken(); // get second word
else
word2 = null;
// note: we just ignore the rest of the input line.
// Now check whether this word is known. If so, create a command
// with it. If not, create a "null" command (for unknown command).
if(commands.isCommand(word1))
return new Command(word1, word2);
else
return new Command(null, word2);
}
/**
* Print out a list of valid command words.
*/
public void showCommands()
{
commands.showAll();
}
}