下面是词法分析的核心代码
public class Analyze {
private String []keyWord = {"if" ,"int","while","else","then","real"};//定义保留字数组
//判断是否为保留字,每次读取的为字符串
public boolean isKeyWord(String ch)
{
for(int i = 0;i < keyWord.length;i++)
if(keyWord[i].equals(ch))
return true;
return false;
}
//判断是否为数字,读取的为字符
public boolean isDigit(char ch)
{
if(ch >= 48 && ch <= 57)
return true;
else
return false;
}
//判断是否为字母,读取的为字符
boolean isLetter(char ch)
{
if((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122) || (ch == 37))
return true;
else
return false;
}
@SuppressWarnings("unchecked")
public void analyze(ArrayList<String> arraylist) throws IOException//核心词法分析算法
{
FileOut writer=new FileOut();//创建一个文件输出流
Iterator<String> it=arraylist.iterator();//定义一个迭代器
String str=null;//str用来接收从文件中读取的一行数据
int row=0;//定义行号,初始值为0
char ch;
while(it.hasNext())//迭代列表中所有的元素,即迭代源文件中所有行的数据交给下面的程序识别
{
int i=0;//定义一个整形变量,用来和整行数据的长度进行比较,以便进行下面的循环
str= it.next().trim();
int col=1;
row++;
while(i<str.length())//这一行还没有识别完
{
ch =str.charAt(i);//读取字符串中的一个字符
if(isLetter(ch))//如果是字母
{
StringBuffer temp = new StringBuffer();//创建一个带缓冲的String对象,存放识别的字母
temp.append(ch);
col++;//追加的时候列数也要加一
ch = str.charAt(++i);
while(isLetter(ch) || isDigit(ch))//继续识别字母后面的一些元素,是否是字母或数字
{
temp.append(ch);
col++;
ch = str.charAt(++i);
}
if(isKeyWord(temp.toString()))//判断是否是关键字
{
int colnum=col-temp.toString().length();
System.out.println(temp + " 为保留字,种别编码为1"+"在第"+row+"行,在第"+colnum+"列");
temp.append(" 为保留字,种别编码为1"+"在第"+row+"行,在第"+colnum+"列");
writer.outPut(temp);
}
else //那么就是标识符
{
int colnum=col-temp.toString().length();
System.out.println(temp + " 为标志符,种别编码为2"+"在第"+row+"行,在第"+colnum+"列");
temp.append(" 为保留字,种别编码为2"+"在第"+row+"行,在第"+colnum+"列");
writer.outPut(temp);
}
}//判断是否是界符
else if((ch == ';') || (ch == '{') || (ch == '}') || (ch == '(') || (ch == ')'))
{
System.out.println(ch + " 为界符,种别编码为3"+"在第"+row+"行,在第"+col+"列");
StringBuffer sb=new StringBuffer();
sb.append(ch);
sb.append(" 为界符,种别编码为3"+"在第"+row+"行,在第"+col+"列");
writer.outPut(sb);
i++;
}
else if(isDigit(ch))//判断是否是数字
{
StringBuffer temp = new StringBuffer();
while(isDigit(ch))//继续识别是不是数字
{
temp.append(ch);
col++;
ch = str.charAt(++i);
}
int colnum=col-temp.toString().length();
System.out.println(temp + " 为常量,种别编码为4"+"在第"+row+"行,在第"+colnum+"列");
temp.append(" 为常量,种别编码为4"+"在第"+row+"行,在第"+colnum+"列");
writer.outPut(temp);
}
else if(ch != ' ')//不为空格时
{
StringBuffer temp = new StringBuffer();
temp.append(ch);
col++;
ch = str.charAt(++i);
if((ch=='=')||(ch=='>')||(ch=='<')||(ch=='!'))//判断是否是算符,
{
temp.append(ch);
col++;
ch = str.charAt(++i);
if(ch=='='){//判断是否是>= == !=
temp.append(ch);
col++;
}
}
if( (ch == '+') || (ch == '-') || (ch == '*') || (ch == '/'))
{
temp.append(ch);
col++;
ch = str.charAt(++i);
i++;
}
int colnum=col-temp.toString().length();
System.out.println(temp + " 为算符,种别编码为5"+"在第"+row+"行,在第"+colnum+"列");
temp.append(" 为算符,种别编码为5"+"在第"+row+"行,在第"+colnum+"列");
writer.outPut(temp);
}
else//当是空格时列也加一
{
i++;
col++;
}
}
}
}
}