Java词法分析器的实现
import import
import
import
import
import
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();
}
}
}
求大神帮我看看 我想实现一个简单的词法分析器