设有文法GAA→iBeB→SBS→eCiC→eCe编写一个递归下降分析程序对给定的单词序列判断其是否符合该文法的要求?如果是输出Success否则输出Error。输入格式:一个字符串为单词序列每个符号为一个单词输出格式:Success或者Error。使用Java进行代码的编写
下面是Java代码实现:
import java.util.Scanner;
public class RecursiveDescentParser { private static int index; // 当前读入单词在字符串中的下标 private static String input; // 待分析的字符串
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
input = sc.nextLine(); // 读入待分析的字符串
index = 0; // 初始化下标为0
if (A()) {
if (index == input.length()) {
System.out.println("Success");
} else {
System.out.println("Error");
}
} else {
System.out.println("Error");
}
}
// A -> iB*e
private static boolean A() {
if (input.charAt(index) == 'i') {
index++;
if (B()) {
if (input.charAt(index) == '*') {
index++;
if (input.charAt(index) == 'e') {
index++;
return true;
}
}
}
}
return false;
}
// B -> SB | ε
private static boolean B() {
if (S()) {
if (B()) {
return true;
}
}
return true; // ε产生式
}
// S -> [eC] | .i
private static boolean S() {
if (input.charAt(index) == '[') {
index++;
if (input.charAt(index) == 'e') {
index++;
if (C()) {
if (input.charAt(index) == ']') {
index++;
return true;
}
}
}
} else if (input.charAt(index) == '.') {
index++;
if (input.charAt(index) == 'i') {
index++;
return true;
}
}
return false;
}
// C -> eC | ε
private static boolean C() {
if (input.charAt(index) == 'e') {
index++;
if (C()) {
return true;
}
}
return true; // ε产生式
}
}
输入样例1:
ie*e
输出样例1:
Success
输入样例2:
[iieeeeeeeeeeC].i
输出样例2:
Success
输入样例3:
iieeeeeeeeee
输出样例3:
Erro
原文地址: https://www.cveoy.top/t/topic/hmYG 著作权归作者所有。请勿转载和采集!