Java词法分析器的实现

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

public class compiler {
static String keyword[]={"main","FILE","int","char","if","else","return","printf","scanf","void","for","while","do","continue","break","include"};
public static boolean isDigit(char ch){
if(ch>='0'||ch<='9')
return true;
else
return false;
}
public static boolean isAlpha(char ch) {
if(ch>='a'&&ch<='z'||ch>='A'&& ch<='Z')
return true;
return false;
}
public static boolean isKey(String word) {
int i= 0;
for(i=0;i<keyword.length;i++){
if(keyword[i].equals(word))
return true;
}
return false;
}
public static void main(String[] args) {
try {
//System.out.println("--------------");
File file = new File("F:\test.txt");
FileInputStream fis = new FileInputStream(file);
//System.out.println("--------------");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String word;
while ((word=br.readLine())!=null) {
StringBuilder stringBuilder = new StringBuilder();
for(int i=0;i<word.length();i++){
char token;
if(Character.isLetter(word.charAt(i))){
token=word.charAt(i);
stringBuilder.append(token);
if(i+1<word.length()&&!Character.isLetter(word.charAt(i+1))) {
if(isKey(stringBuilder.toString())){
System.out.println("关键字:"+stringBuilder);
}
else {
System.out.println("普通标识符:"+stringBuilder);
}
stringBuilder.setLength(0);
}

}
else if (isDigit(word.charAt(i))) {
token=word.charAt(i);
stringBuilder.append(token);
if(i+1<word.length()&&!isDigit(word.charAt(i+1))){
System.out.println("无符号实数"+stringBuilder);
stringBuilder.setLength(0);
}
}
else{
token=word.charAt(i);
switch (token) {
case '[':
case ']':
case '{':
case '}':
case ',':
case ':':
case ';':
case '(':
case ')':System.out.println("分界符:"+token);
break;
case'=':System.out.println("运算符:"+token);
break;
default:System.out.println("无法识别字符:"+token);
break;
}
}
}

}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}
不知道哪里逻辑错误了 希望有人能帮忙看看 万分感谢

2个回答

不多说,直接贴代码
package edu.software.compile;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**

  • 1 基本字
  • 2 标识符
  • 3 常数
    ......
    答案就在这里:Java 实现词法分析器(编译原理)
    ----------------------Hi,地球人,我是问答机器人小S,上面的内容就是我狂拽酷炫叼炸天的答案,除了赞同,你还有别的选择吗?
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问