递归下降分析程序实现文法识别
import java.util.Scanner;
public class RecursiveDescentParser {
private static String input; // 待分析的单词序列
private static int index; // 当前分析到的单词的下标
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
input = scanner.nextLine(); // 读入单词序列
index = 0; // 从第一个单词开始分析
if (A()) { // 如果符合文法
System.out.println("Success");
} else {
System.out.println("Error");
}
}
// A → i B* e
private static boolean A() {
if (input.charAt(index) == 'i') { // 匹配 i
index++;
if (B()) { // 匹配 B*
if (input.charAt(index) == 'e') { // 匹配 e
index++;
return true; // 符合文法
}
}
}
return false; // 不符合文法
}
// B → S B | e
private static boolean B() {
if (S()) { // 匹配 S
if (B()) { // 匹配 B
return true; // 继续匹配
}
return true; // B 可以为空
}
return false; // 不符合文法
}
// S → [ e C ] | . i
private static boolean S() {
if (input.charAt(index) == '[') { // 匹配 [
index++;
if (input.charAt(index) == 'e') { // 匹配 e
index++;
if (C()) { // 匹配 C
if (input.charAt(index) == ']') { // 匹配 ]
index++;
return true; // 符合文法
}
}
}
} else if (input.charAt(index) == '.') { // 匹配 .
index++;
if (input.charAt(index) == 'i') { // 匹配 i
index++;
return true; // 符合文法
}
}
return false; // 不符合文法
}
// C → e C | e
private static boolean C() {
if (input.charAt(index) == 'e') { // 匹配 e
index++;
if (C()) { // 匹配 C
return true; // 继续匹配
}
return true; // C 可以为空
}
return false; // 不符合文法
}
}
原文地址: https://www.cveoy.top/t/topic/oPRX 著作权归作者所有。请勿转载和采集!