自己参考了网上的代码写了如下的LR0分析,断断续续写了一个星期才完成的,可以直接运行,代码的算法和主流算法不同,很有可能有错,水平所限,望见谅。
Analyze.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
public class Analyze {
public HashMap<Character, ArrayList<String>> experssionSet = new HashMap<Character, ArrayList<String>>();
public ArrayList<Character> VnList = new ArrayList<Character>();// A S B 非终结符
public ArrayList<Character> VtList = new ArrayList<Character>();// a b
public ArrayList<Character>List = new ArrayList<Character>();// a b
@SuppressWarnings("unchecked")
public ArrayList<Item> stateClass[] = new ArrayList[20];
public ArrayList<Item> items = new ArrayList<Item>();
public ArrayList<Item> flag = new ArrayList<Item>();//有没有被归入新一队过
public String[][] DFA = new String[8][6];
//public HashMap<Item, Integer> stateItem = new HashMap<Item, Integer>();
public HashMap<Integer, ArrayList<Item>> itemClass = new HashMap<Integer, ArrayList<Item>>();
public ArrayList<Item> stateItems = new ArrayList<Item>();
public int totalState;
public void closure(Item I) {
int a;
int b;
ArrayList<Item> J = new ArrayList<Item>();
ArrayList<Item> temp = new ArrayList<Item>();
J.add(I);
//System.out.println("\n传入的I:");
//I.printItem();
flag.add(I);
if(I.getIndex() == I.getRight().length()) {
itemClass.put(totalState, J);
return ;
}
else{
do {
a = J.size();
temp.clear();
for (Item j:J){
for(Item i:items) {
if(i.getIndex()==0&&!J.contains(i)) {
if(j.getRight().charAt(j.getIndex())==i.getLeft()) {
temp.add(i);
flag.add(i);
}
}
}
}
J.addAll(temp);
b = J.size();
if(b == a) {
itemClass.put(totalState, J);
return;
}
}while(true);
}
}
public String goto_fun_vt(int state,char X) {
ArrayList<Item> I = new ArrayList<Item>();
I = itemClass.get(state);
int index ;
int r_count = 0;
for(Item i:I) {
index = i.getIndex();
if(index<i.getRight().length()) {
if(i.getRight().charAt(index)==X) {
for(int count=0;count<totalState;count++) {
for(Item j:itemClass.get(count)) {
if((j.getRight().equals(i.getRight())&&j.getLeft().equals(i.getLeft()))
&&j.getIndex()==index+1) {
return "s"+String.valueOf(count)