Switch or if statements in writing an interpreter in java

后端 未结 2 970
有刺的猬
有刺的猬 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: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 directives = new HashMap();
    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.

提交回复
热议问题