www.pudn.com > grammaranalyse.rar > AccAnalyse.java
package jywhu;
import java.io.*;
import java.util.*;
public class AccAnalyse {
private ArrayList al;
private static int i=0;
private static final String[] reserveWord={"if","else","while","read","write","int","real"};
private String str;
private static int lineCount=0;
private int index=0;
private String token;
public AccAnalyse(String str){
this.str=str;
al=new ArrayList();
}
/*public ArrayList getList(){
return al;
}*/
public void analyse(){
File f=new File(str);
try{
if(!f.exists()){
System.out.println("源文件不存在");
}else{
BufferedReader br=new BufferedReader(new FileReader(f));
String s;
//开始词法分析
while((s=br.readLine())!=null){
lineCount++;
//过滤行字符串
s=s.trim();
System.out.println(lineCount + ":" + s);
char[] c=s.toCharArray();
while(index'){
index++;
token=this.contact(token, ch);
//System.out.println(" " + " " + lineCount + ":" + token );
al.add(new Token("relop",token,lineCount));
}else{
//System.out.println(" " + " " + lineCount + ":" + token );
al.add(new Token("relop",token,lineCount));
}
this.retract();
token=" ";
break;
case '-':
token=this.contact(token, ch);
// System.out.println(" " + " " + lineCount + ":" + token );
al.add(new Token("addop",token,lineCount));
token=" ";
break;
case '/':
token=this.contact(token, ch);
//System.out.println(" " + " " + lineCount + ":" + token );
al.add(new Token("mulop",token,lineCount));
token=" ";
break;
case ',':
token=this.contact(token, ch);
//System.out.println(" " + " " + lineCount + ":" + token );
al.add(new Token("comma",token,lineCount));
token=" ";
break;
case ';':
token=this.contact(token, ch);
// System.out.println(" " + " " + lineCount + ":" + token );
al.add(new Token("semicolon",token,lineCount));
token=" ";
break;
default:
token=this.contact(token, ch);
System.out.println(" " + " " + lineCount + ":" +
"[ERROR]在此行发现不能识别的单词,此行分析终止!" + " " + token);
token=" ";
break;
}
}
index=0;
}
}
}catch(Exception e){
e.printStackTrace(); }
}
//得到一个字符
public char getChar(char[] c){
try{
while((c[index]) == ' '){
index++;
}
index++;
}catch(Exception e){
e.printStackTrace();
}
return c[index-1];
}
//得到先前字符的后一个字符
public char getNextChar(char[] c){
index++;
return c[index-1];
}
public boolean isLetter(char ch){
return Character.isLetter(ch);
}
public boolean isDigit(char ch){
return Character.isDigit(ch);
}
//判断此字符串是否为保留字
public boolean isReserve(String token){
for(int i=0;i