Switch or if statements in writing an interpreter in java

后端 未结 2 916
有刺的猬
有刺的猬 2021-01-29 01:41

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 i

相关标签:
2条回答
  • 2021-01-29 02:02

    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
           ...
    }
    
    0 讨论(0)
  • 2021-01-29 02:07

    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.

    0 讨论(0)
提交回复
热议问题