代码:
package analyzer;
import java.util.*;
public class Table {
static Scanner in = new Scanner(System.in);
static String endChar,misendChar;
static int num;
public static void main(String[] args) {
System.out.println("请输入终结符:");
endChar = in.next();
System.out.println("请输入非终结符:");
misendChar = in.next();
System.out.println("请输入文法个数:");
num = in.nextInt();
String[] grammer = new String[num];
for(int i=0;i<num;i++) {
System.out.println("请输入第"+(i+1)+"个:");
grammer[i] = in.next();
}
int col = endChar.length()+misendChar.length()+1;
System.out.println("请输入分析表的行数:");
int row = in.nextInt();
System.out.println("请输入LR(0)分析表:");
String[][] table = new String[row][col];
String title="";
for(int i=0;i<endChar.length();i++) {
title+=endChar.charAt(i)+"\t";
}
title+="#\t";
for(int i=0;i<misendChar.length();i++) {
title+=misendChar.charAt(i)+"\t";
}
System.out.println("序号\t"+title);
for(int i=0;i<row;i++) {
System.out.print(i+"\t");
for(int j=0;j<col;j++) {
table[i][j] = in.next();
if (j==col-1) {
System.out.println("\n");
}else {
System.out.print("\t");
}
}
}
System.out.println("请输入待测字符串:");
String s= in.next();
System.out.println("分析过程如下:");
String title1 = "步骤\t状态\t栈中符号\t余留子串\t分析动作\t下一状态";
Stack<Character> contiditon = new Stack<Character>();
Stack<Character> stackChar = new Stack<Character>();
Stack<Character> lastChar = new Stack<Character>();
String action="";
char nextAction = 0;
lastChar.push('#');
for(int i=s.length()-1;i>=0;i--) {
char c=s.charAt(i);
lastChar.push(c);
}
stackChar.push('#');
contiditon.push('0');
System.out.println(title1);
int r;
int h = 1;
while(action.equals("acc")==false) {
r = contiditon.peek()-'0';
char ch2 = lastChar.peek();
int index = title.indexOf(ch2)/2;
String st = table[r][index];
if(st.equals("-")) {
System.out.println("Error,pleace check!");
break;
}else {
action = st;
System.out.print(h+"\t"+posString(contiditon)+"\t"+posString(stackChar)+"\t"+posString(lastChar)+"\t"+action+"\t");
if(st.charAt(0)=='s') {
nextAction = st.charAt(1);
System.out.println(nextAction+"\t");
contiditon.push(nextAction);
stackChar.push(ch2);
lastChar.pop();
}else if(st.charAt(0)=='r') {
int m = st.charAt(1)-'0';
String gram = grammer[m];
for(int p=0;p<gram.length()-3;p++) {
stackChar.pop();
contiditon.pop();
}
stackChar.push(gram.charAt(0));
int x = contiditon.peek()-'0';
int y = title.indexOf(gram.charAt(0))/2;
String n = table[x][y] ;
nextAction = n.charAt(0);
contiditon.push(nextAction);
System.out.println(nextAction+"\t");
}
h++;
}
}
}
public static String posString(Stack<Character> stack) {
String s ="";
for(char ch:stack) {
s+=ch;
}
return s;
}
}
图片: