LL(1)语法分析程序的设计 编译原理 java
1)完成对文法及LL(1)预测分析表的存储和处理;
2)编写LL(1)语法分析程序,接受字符串的输入,判断该字符串是否为该文法的合法句子,并输出完整的分析过程;
3)用C#或JAVA语言实现;
源码
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("输入串:");
Scanner input = new Scanner(System.in);
String str = input.nextLine();
int len = str.length();
char []s = str.toCharArray();
Analyse analyse = new Analyse();
analyse.anlyse(s,len);
}
}
public class G {
private char []row = {'i','+','*','(',')','#'};
private char []line = {'E','M','T','N','F'};
public int findRow(char r){
for(int i =0;i<row.length;i++){
if(r == row[i] ){
return i;
}
}
return -1;
}
public int findLine(char l){
for(int i =0;i < line.length;i++){
if(l == line[i]){
return i;
}
}
return -1;
}
}
import java.util.Stack;
public class Analyse {
private Stack<String> stack=new Stack<String>();
private String [][]LL1 = {
{"->TM","null","null","->TM","null","null"},
{"null","->+TM","null","null","->$","->$"},
{"->FN","null","null","->FN","null","null"},
{"null","->$","->*FN","null","->$","->$"},
{"->i","null","null","null","(E)","null"}
};
public void anlyse(char str[],int len){
G g = new G();
int x,y;
int i = 0;
char s;//栈顶
stack.push("#");
stack.push("E");
while(i<len){
s = stack.peek().charAt(0);
if(s >= 65 && s <= 90){
x = g.findRow(str[i]);
y = g.findLine(s);
if(x != -1 && y != -1){
int len2 = LL1[y][x].length();
if(LL1[y][x].equals("null")){
System.out.println("报错");
break;
}
else if(!(LL1[y][x]=="->$")){
stack.pop();
for(int m = len2-1; m > 1;m--){
String ss = LL1[y][x].charAt(m)+"";
stack.push(ss);
}
}
else {
stack.pop();
}
System.out.println(s+""+ LL1[y][x]);
}else{
System.out.println("报错!");
break;
}
}else{
if(s == str[i] ){
stack.pop();
if(s == '#' &&str[i]== '#'){
System.out.println("接受");
return;
}
System.out.println(s+"匹配");
i++;
}else{
System.out.println("报错!!");
break;
}
}
}
}
}