递归下降的语法分析
接上一篇 递归下降的预则分析法
这次直接用递归实现的,有多个产生式直接回溯,没有进行预测分析
package test;
import java.util.Scanner;
class Solution {
    int p = 0;
    char[] input;
    void E() throws Exception {
        T();
        E1();
    }
    void E1() throws Exception {
        int p1 = p;//把p备份,回溯回来时用
        try {
            if (p >= input.length || input[p] != '+') throw new YufaException();//就算到最后一个字符了,还是可以用空产生式替换
            p++;
            T();
            E1();
        } catch (YufaException e) {//应用空产生式
            p = p1;
        }
    }
    void T() throws Exception {
        F();
        T1();
    }
    void T1() throws Exception {
//        System.out.print("|");
        int p1 = p;//把p备份,回溯回来时用
        try {
            if (p >= input.length || input[p] != '*') throw new YufaException();
            p++;
            F();
            T1();
        } catch (YufaException e) {
            p = p1;
        }
    }
    void F() throws Exception {
        int p1 = p;//把p备份,回溯回来时用
        try {
            if (input[p] != '(') throw new YufaException();
            p++;
            E();
            if (input[p] != ')') throw new YufaException();
            p++;
        } catch (YufaException e) {
            p = p1;
            if (input[p] == 'i') p++;
            else throw new YufaException();
        }
    }
    void test() throws Exception {
        p = 0;
        E();
        if (input.length == p)//当分析到最后一个字符即成功
            System.out.println("accept");
        else System.out.println("illeagal");
    }
    public static void main(String[] args) throws Exception {
        Solution solution = new Solution();
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            String s = in.next();
            solution.input = s.toCharArray();
            solution.test();
        }
    }
}
class YufaException extends Exception {
    public YufaException() {
        super("语法错误");
    }
}
 
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号