现在有没有充分的理由使用数字来识别令牌?我正在关注Crafting a Compiler
。
作者提供的代码在这里:
public class Token {
public final static int ID = 0, FLTDCL = 1, INTDCL = 2, PRINT = 3,
ASSIGN = 4, PLUS = 5, MINUS = 6, EOF = 7, INUM = 8, FNUM = 9;
public final static String[] token2str = new String[] { "id", "fltdcl",
"intdcl", "print", "assign", "plus", "minus", "$", "inum", "fnum" };
public final int type;
public final String val;
public Token(int type) {
this(type, "");
}
public Token(int type, String val) {
this.type = type;
this.val = val;
}
public String toString() {
return "Token type\t" + token2str[type] + "\tval\t" + val;
}
}
不是使用丑陋的数组,修改构造函数以接受type
变量而不是整数的字符串是不是更明智?然后我们就可以摆脱
public final static int ID = 0, FLTDCL = 1, INTDCL = 2, PRINT = 3,
ASSIGN = 4, PLUS = 5, MINUS = 6, EOF = 7, INUM = 8, FNUM = 9;
或者是否需要以后使用字符串会更糟?
答案 0 :(得分:2)
有几个好处:
switch
int
而不是字符串。