资源描述:
《编译原理_词法分析器》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、一、实验目的和要求:设计并实现一个JAVA语言的词法分析程序,加深对词法分析原理的理解。二、实验原理:词法分析是从左向右扫描每行源程序的符号,拼成单词,换成统一的机内表示形式——TOKEN字,送给语法分析程序。2TOKEN字是一个二元式:(单词种别码,自身值)三、实验步骤与要求1、设计的词法分析器符合软件工程的要求。2、编制程序,此程序应具有如下功能:1)输入:字符串(待进行词法分析的源程序),输出:由(种别码,自身值)所组成的二元组序列。2)功能:a.滤空格b.识别保留字c.识别标识符四、试验设计和算法分析:实验原理:程序流程:置初值→调用扫描子程序→输出串结束→输出
2、单词二元组→是→否→结束 词法分析主程序示意图待分析的简单语言的词法(1) 关键字:"abstract","assert","boolean","break","byte","case","catch","char","class","continue","default","do","double","else","enum","extends","final","finally","float","for","if","implements","import","instanceof","int","interface","long","native","new",
3、"package","private","protected","public","return","strictfp","short","static","super","switch","synchronized","this","throw","throws","transient","try","void","volatile","while"所有关键字都是小写。(2)运算符和界符: "=","+","-","*","/","<",">","<=",">=","==","!=","!""(",")","[","]","{","}",";","/*","*/","
4、//"设计的词法分析器符合软件工程的要求。2、编制程序,此程序应具有如下功能:1)输入:字符串(待进行词法分析的源程序),输出:由(种别码,自身值)所组成的二元组序列。2)功能:a.滤空格b.识别保留字c.识别标识符词法分析程序的算法思想算法的基本任务是从字符串表示的源程序中识别出具有独立意义的单词符号,其基本思想是根据扫描到单词符号的第一个字符的种类,拼出相应的单词符号。三、代码:packagecom.huke.lpascal;importjava.util.Scanner;/***词法分析器:输入源程序,输出单词符号。*输入:字符串(待进行词法分析的源程序),输出:
5、由(种别码,自身值)所组成的二元组序列。*@authorwnp**/publicclassLexical{/***@paramargs*/publicLexical(){}//构造函数//定义一个保存关键字的字符串数组String[]keyWords=newString[]{"abstract","assert","boolean","break","byte","case","catch","char","class","continue","default","do","double","else","enum","extends","final","finally
6、","float","for","if","implements","import","instanceof","int","interface","long","native","new","package","private","protected","public","return","strictfp","short","static","super","switch","synchronized","this","throw","throws","transient","try","void","volatile","while"};//定义一个保存运算符的字
7、符串数组String[]operators=newString[]{"=","+","-","*","/","<",">","<=",">=","==","!=","!"};//定义一个保存界符的字符串数组String[]delimiter=newString[]{"(",")","[","]","{","}",";","/*","*/","//"};//定义一个判断字符串是否为关键字的函数publicbooleanisKeyWords(Stringstr){for(inti=0;i