编译原理 语法分析(递归下降法 Java)小案例
package syntaxAnalysis;
public class Parser {
private int index = 0;
private String token = "";
public Parser(){
}
public void setToken(String str) {
this.token = str;
}
public void E() {
T();
X();
}
public void T() {
F();
Y();
}
public void X() {
if (token.charAt(index) == '+') {
System.out.print(token.charAt(index));
index++;
T();
X();
} else if(token.charAt(index) == '\0'){
} else {
}
}
public void Y() {
if (token.charAt(index) == '*') {
System.out.print(token.charAt(index));
index++;
F();
Y();
} else if(token.charAt(index) == '\0'){
} else {
}
}
public void F() {
if (token.charAt(index) == '(') {
System.out.print(token.charAt(index));
index++;
E();
if(token.charAt(index) == ')')
index++;
else
System.out.println("error");
} else if (token.charAt(index) == 'i') {
System.out.print(token.charAt(index));
index++;
} else {
}
}
public void analyse() {
E();
}
public static void main(String[] args){
Parser parser = new Parser();
parser.setToken("i+i*i\0");
parser.analyse();
}
}
参考:编译原理 实验3 递归下降语法分析程序设计