在java中编写解释器的switch或if语句
当前的任务需要我编写一个程序来读取包含指令的文件,该指令使用一种非常微小且基本的编程语言(行为有点像 FORTRAN)并执行这些指令.基本上它是我猜想的语言的简单解释器.它是完全线性的,所有语句都按顺序定义,并且只有字符串和整数变量.如果它们存在于源文件中,我需要查找并定义 8 个关键字和 4 个算术运算符,并且每一行必须以保留字之一开始.这种语言的程序可能看起来像这样:
Current assignment needs me to write a program to read a file with instructions in a very tiny and basic programming language (behaves a little like FORTRAN) and execute those instructions. Basically it's a simple interpreter for the language I guess. It's completely linear, with statements all being defined in sequence and it only has String and integer variables. There are 8 keywords and 4 arithmetic operators I would need to find and define if they exist within the source file, and each line must start off with one of the reserved words. A program in this language might look something like this:
#COMMENTS
LET.... (declares variables with values)
INTEGER myINT
STRING myString
CALCULATE...
PRINT
PRINTLN
END
我可以使用 switch 块而不是 if 循环来查找然后执行所有这些吗?我担心的是开关不适用于 Java 6 中的字符串,这是我应该使用的,但我看不到如何轻松分配各种 int 值以便开关块起作用.提前感谢您的任何建议和建议!
Can I use a switch block instead of if-loops to find and then execute all these? My concern is that switches don't work with Strings in Java 6, which is what I'm supposed to be using, but I don't see how to easily assign various int values so the switch block would work. Thanks in advance for any suggestions and advice!
推荐答案
如果您的语言非常简单,以至于每个语句都以自己的行开头并且仅由一个单词标识,那么(正如 Gray 在另一条评论中指出的那样)您可以拆分每行中的单词,然后将第一个单词与地图进行比较.但是,我建议不要将单词映射到整数,然后进行一次大切换,而是将它们映射到对象中,如下所示(由 Dave Newton 建议):
If your language is so simple that every statement begins in its own line and is identified by one word only, then (as Gray pointed out in another comment) you can split the words in each line, then compare the first word against a map. However, I would suggest, instead of mapping the words to ints and then doing one big switch, to map them into objects instead, like this (suggested by Dave Newton):
interface Directive {
public void execute(String line);
}
class LetDirective implements Directive {
public void execute(String line) { ...handle LET directive here... }
}
...define other directives in the same way...
然后定义地图:
private Map<String, Directive> directives = new HashMap<String, Directive>();
directives.put("LET", new LetDirective());
...
然后在你的解析方法中:
Then in your parsing method:
int firstSpace = line.indexOf(' ');
String command = line;
if (firstSpace > 0)
command = line.substring(0, firstSpace);
Directive directive = directives.get(command.toUpperCase());
if (directive != null)
directive.execute(line);
else
...show some error...
每个指令都必须自己解析该行的其余部分,并在其 execute() 方法中正确处理.
Each directive would have to parse the rest of the line on its own and handle it correctly inside its execute() method.
与切换相比,这样做的好处是您可以处理大量命令,而无需使用一种庞大的方法,而是每个命令使用一种较小的方法.
The benefit of this over a switch is that you can handle a larger amount of commands without ending up with one gigantic method, but instead with one smaller method per each command.
相关文章