您的位置:首页 > 编程语言

LL(1)文法的实现代码(可报错处理)

2016-11-18 16:01 267 查看
先定义一个分析表

public class Table {
private String[][] table = { { "", "", "", "", "", "" }, { "", "", "", "", "", "" }, { "", "", "", "", "", "" },
{ "", "", "", "", "", "" }, { "", "", "", "", "", "" } };

public Table() {
table[0][0] = "Te";
table[0][3] = "Te";
table[1][1] = "+Te";
table[1][4] = "!";
table[1][5] = "!";
table[2][0] = "Ft";
table[2][3] = "Ft";
table[3][1] = "!";
table[3][2] = "*Ft";
table[3][4] = "!";
table[3][5] = "!";
table[4][0] = "id";
table[4][3] = "(E)";
table[0][4]="s";
table[0][5]="s";
table[2][1]="s";
table[2][4]="s";
table[2][5]="s";
table[4][1]="s";
table[4][2]="s";
table[4][4]="s";
table[4][5]="s";
}

int tranToNum(String s) {
switch (s) {
case "E":
case "id":
return 0;
case "e":
case "+":
return 1;
case "T":
case "*":
return 2;
case "t":
case "(":
return 3;
case "F":
case ")":
return 4;
case "#":
return 5;
}
return -1;
}

String match(String ll, String str) {
return table[tranToNum(ll)][tranToNum(str)];
}
}
再定义一个运行类

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;

public class ToptoDown {

public static void main(String[] args) {
List<String> ter = new ArrayList<String>();
ter.add("id");
ter.add("+");
ter.add("*");
ter.add("(");
ter.add(")");
// TODO Auto-generated method stub
Table table = new Table();
String str;
Scanner input = new Scanner(System.in);
str = input.nextLine();
Stack<String> stack = new Stack();
stack.push("#");
stack.push("E");
int i = 0;
String ss = str.substring(i, i + 1);
if (ss.equals("i")) {
i++;
ss += str.substring(i, i + 1);
}
i++;
String ll = stack.peek();
while ( !ll.equals("#")) {
System.out.println(ll+" "+ss);
if (ll.equals(ss)) {
stack.pop();
ss = str.substring(i, i + 1);
if (ss.equals("i")) {
i++;
ss += str.substring(i, i + 1);
}
i++;
ll = stack.peek();
} else {
if (ter.contains(ll)) {
stack.pop();
ll = stack.peek();
System.out.println("终结符不匹配,跳过"+ll);
continue;
}
String mat = table.match(ll, ss);
if (mat.length() == 0) {
System.out.println("查表为空,跳过"+ss);
ss = str.substring(i, i + 1);
if (ss.equals("i")) {
i++;
ss += str.substring(i, i + 1);
}
i++;
continue;
} else if (mat.equals("s")) {
System.out.println("同步,弹出"+ll);
stack.pop();
ll = stack.peek();
continue;
} else {
System.out.println(ll + " -> " + mat);
stack.pop();
if (!mat.equals("!")) {
int len = mat.length();
for (; len > 0; len--) {
String sl = mat.substring(len - 1, len);
if (sl.equals("d")) {
len--;
String sll = mat.substring(len - 1, len) + sl;
sl = sll;
}
stack.push(sl);
}
}
ll = stack.peek();
}

}
}
while(!ss.equals("#")) {
System.out.println("结尾多了"+ss);
ss= str.substring(i, i + 1);
i++;
}
}

}
当做借鉴
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java LL1