这个是看MOOC学编译原理的一个作业。
识别标识符和关键字,核心在于转移图,dfa的构造
package bingone;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
/**
* 手工构造词法分析器,标注的关键字有if for 。
* @author bingone
*
*/
enum Token{
FOR("for"),
IF("if");
String name;
private Token(String name){
this.name = name;
}
}
public class ManualToken {
/**
* 对应转移图有 空 0, i 1, if 2,f 3,fo 4, for,5, 其他 6
* @param row
* @param str
*/
private static void solve(int row,String str){
int cnt = 0;
int tag = 0;
str = new String(str+" ");
char [] token = new char[100];
for(int i = 0;i<str.length();i++){
char ch = str.charAt(i);
if(ch ==‘ ‘){
if(tag != 0){
if(tag==6){
System.out.print( "ID("+new String(token, 0, cnt) +")");
}else if(tag==2){
System.out.print(Token.IF);
}else if(tag==5){
System.out.print(Token.FOR);
}
System.out.println( "("+row+","+ (i-cnt+1) + ")" );
}
cnt = 0;
tag = 0;
continue;
}
token[cnt++] = ch;
if(tag == 0){
switch(ch){
case ‘i‘:tag = 1;break;
case ‘f‘:tag = 3;break;
default: tag = 6;break;
}
}else if(tag == 1){
if(ch==‘f‘) tag = 2;
else tag = 6;
}else if(tag ==2) tag = 6;
else if(tag==3){
if(ch==‘o‘) tag = 4;
else tag = 6;
}else if(tag==4){
if(ch==‘r‘) tag = 5;
else tag = 6;
}
}
}
public static void main(String[] args) throws Exception {
// System.out.println(System.getProperty("user.dir"));
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("./src/bingone/in.txt"))) ;
String aline = null;
int row = 1;
while((aline = br.readLine()) != null){
solve(row++,aline);
}
}
}
时间: 2024-09-29 23:48:53