Switch or if statements in writing an interpreter in java

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

提交回复
热议问题