加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
Parser.java 2.04 KB
一键复制 编辑 原始数据 按行查看 历史
luyanfei78 提交于 2020-05-06 08:43 . initial commit.
import java.util.Scanner;
/**
* This class is part of the "World of Zuul" application.
* "World of Zuul" is a very simple, text based adventure 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 Kölling and David J. Barnes
* @version 2016.02.29
*/
public class Parser
{
private CommandWords commands; // holds all valid command words
private Scanner reader; // source of command input
/**
* Create a parser to read from the terminal window.
*/
public Parser()
{
commands = new CommandWords();
reader = new Scanner(System.in);
}
/**
* @return The next command from the user.
*/
public Command getCommand()
{
String inputLine; // will hold the full input line
String word1 = null;
String word2 = null;
System.out.print("> "); // print prompt
inputLine = reader.nextLine();
// Find up to two words on the line.
Scanner tokenizer = new Scanner(inputLine);
if(tokenizer.hasNext()) {
word1 = tokenizer.next(); // get first word
if(tokenizer.hasNext()) {
word2 = tokenizer.next(); // get second word
// 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);
}
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化