学java没多久写了个LL(1)语法分析器,基本原理是根据预测分析表生成产生式,提示数组下标越界!希望大家帮忙看看!
class LL1test{
public static void main(String[] args)
{
char str[]=new char[20];
int i=0,n=0;
// char s[]=new char[10];
char ch;
//int i=0,j=0,k=0;
String str1="";
System.out.println("请输入句子,以#结束!");
while(true)
{
try{
str[i]=(char)System.in.read();
}
catch(Exception e){}
if(str[i]=='#') break;i++;
}
n=i+1;
ch=str[0];
for(i=0;i<n;i++)
str1+=str[i];
System.out.println("分析结果如下:");
YuFa yufa=new YuFa(str1,n,ch,'#','S');
}
}
class YuFa{
private int i;
private int j=0;
private int k;
private int m;
private char s[]=new char[20];
// s[0]='#';s[1]='S';
private char top;
private char ch;
Perror error=new Perror();
public YuFa(String s1,int n,char c,char c1,char c2)
{ ch=c;
s[0]=c1;
top=s[1]=c2;
char str[] = s1.trim().toCharArray();
while(j<n)
{
if(top=='i'||top=='+'||top=='*'||top=='('||top==')'||top=='#')
{
if(top=='#'&&ch=='#')
{
System.out.println("OK!");System.exit(0);
}
else if(top==ch)
{
j++;
//top=s[i--];
top=s[--i];
ch=str[++m];
}
else error.print();
}
else if(top=='S'||top=='A'||top=='B'||top=='C'||top=='D'||top=='E')
{
k=number(top);
switch(k)
{
case 1: S(ch); break;
case 2: A(ch); break;
case 3: B(ch); break;
case 4: C(ch); break;
case 5: D(ch); break;
case 6: E(ch); break;
default: break;
}
}
}
}
public int number(char c)
{
if(c=='S') return 1;
else if(c=='A') return 2;
else if(c=='B') return 3;
else if(c=='C') return 4;
else if(c=='D') return 5;
else if(c=='E') return 6;
else
System.out.println("输入错误!");return 0;
}
public void S(char ch)
{
if(ch=='('||ch==')')
{
System.out.println("S::=A");
top='A';
}
else error.print();
}
public void A(char ch)
{
if(ch=='('||ch==')')
{
System.out.println("A::=BA'");
s[i++]='D';top=s[i]='B';
}
else error.print();
}
public void B(char ch)
{
if(ch=='('||ch==')')
{
System.out.println("B::=CB'");
s[i++]='E';top=s[i]='C';
}
else error.print();
}
public void C(char ch)
{
if(ch=='(')
{
System.out.println("C::=(");
top=s[i]='(';
}
else if(ch==')')
{
s[i++]='*';
s[i++]='A';
top=s[i]=')';
}
else error.print();
}
public void D(char ch)
{
if(ch=='i')
{
System.out.println("A'::=iBA'");
s[i++]='D';s[i++]='B';top=s[i]='i';
}
else if(ch=='*'||ch=='#')
{
System.out.println("A'::=e");
top=s[--i];
// top=s[i--];
}
/*else if(ch=='#')
{
System.out.println("A'::=e");
// top=s[--i];
top=s[i--];
}*/
else error.print();
}
public void E(char ch)
{
if(ch=='i')
{
System.out.println("B'::=e");
top=s[--i];
// top=s[i--];
}
else if(ch=='+')
{
System.out.println("B'::=+CB'");
s[i++]='E';s[i++]='C';top=s[i]='+';
}
else if(ch=='*'||ch=='#')
{
System.out.println("B'::=e");
top=s[--i];
//top=s[i--];
}
else error.print();
}
}
class Perror{
public void print()
{
System.out.println("该句子不能由文法产生!");System.exit(0);
}
}
写的不好大家见谅!有什么好意见提出来,不胜感激!