Switch or if statements in writing an interpreter in java

ε祈祈猫儿з 提交于 2019-12-02 11:23:56

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...

Then define the map:

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...

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.

If you are talking about converting strings to integers then you could do it with an Java enumerated type:

private enum ReservedWord {
   LET,
   ...
}

// skip blank lines and comments
String[] tokens = codeLine.split(" ");
ReservedWord keyword;
try {
   keyword = ReservedWord.valueOf(tokens[0]);
} catch (IllegalArgumentException e) {
   // spit out nice syntax error message
}

You could also put the processing of the line inside of the enum as a method if you'd like. You could also do it with a Map:

private final Map<String, Integer> reservedWords = new HashMap<String, Integer>();
private final int RESERVED_WORD_LET 1
...
{
   reservedWords.put("LET", RESERVED_WORD_LET);
   ...
}

// skip blank lines and comments
String[] tokens = codeLine.split(" ");
Integer value = reservedWords.get(tokens[0]);
if (value == null) // handle error... ;
switch (value) {
   case 1:
       // LET
       ...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!