Ace_Gp
kuop4wn
采纳率50%
2015-11-22 12:25 阅读 2.6k

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条回答 默认 最新

  • CSDNXIAOS Robot-S 2015-11-22 12:31

    不多说,直接贴代码
    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,上面的内容就是我狂拽酷炫叼炸天的答案,除了赞同,你还有别的选择吗?
    点赞 1 评论 复制链接分享
  • devmiao devmiao 2015-11-22 18:49

相关推荐