用JAVA写词法分析器(共3页).doc
精选优质文档-倾情为你奉上import java.lang.*;import java.io.*;public class Wordanalsys static char ch; static int index=0; static int j=0; static char allstr=new char; static String name; public char Getchar() try ch=(char)System.in.read(); catch(Exception e)e.printStackTrace(); return ch; public boolean IsLetter(char ch) return java.lang.Character.isLetter(ch); public boolean IsDigit(char ch) return java.lang.Character.isDigit(ch); public int Reserve() KeyTable table=new KeyTable5; table0=new KeyTable("while",1); table1=new KeyTable("for",2); table2=new KeyTable("if",3); table3=new KeyTable("else",4); table4=new KeyTable("int",5); name=new String(allstr).substring(j,index);/取子串 for(int i=0;i<5;i+) if(name.equals(tablei.key) return tablei.code; return 0; public static void main (String args) Wordanalsys a=new Wordanalsys(); ch=a.Getchar(); int m=0; while(ch!='#') allstrindex=ch; index+; ch=a.Getchar(); int k=index; index=0; while(j<k-1) m=j; if(a.IsLetter(allstrj) while(a.IsLetter(allstrindex)|a.IsDigit(allstrindex) index+; if(a.Reserve()!=0) System.out.println("保留字 "+name+" "+a.Reserve(); else System.out.println("标识符 "+" 6"); j=index; if(a.IsDigit(allstrj) while(a.IsDigit(allstrindex)index+; name=new String(allstr).substring(j,index); int b=java.lang.Integer.pasint(name); String name1=Integer.toBinaryString(b) ; System.out.println("数字 "+name+" 7"+name1); j=index; if(allstrj='(')System.out.println("左括号 "+"( 8");index+;j=index; if(allstrj='=')System.out.println(" 等号 "+"= 9");index+;j=index; if(allstrj=')')System.out.println("右括号 "+") 10");index+;j=index; if(allstrj=' ')while(allstrj=' ')index+;j=index; if(allstrj='')System.out.println("分号"+" ; 11");index+;j=index; if(allstrj='<')index+;j=index; if(allstrj='=') System.out.println("小于等于"+" <= 12");index+;j=index; else System.out.println("小于 "+" < 13"); if(allstrj='>')index+;j=index; if(allstrj='=') System.out.println("大于等于"+" >= 15");index+;j=index ; elseSystem.out.println("大于号"+" > 14" ); if(allstrj='+')index+;j=index; if(allstrj='+') System.out.println("自增运算符"+" + 16");index+;j=index; else System.out.println("加号"+" + 17"); if(allstrj='-')index+;j=index; if(allstrj='-') System.out.println("自减运算符"+" - 16");index+;j=index; else System.out.println("减号"+" - 17"); if(allstrj='n')System.out.println("enter the next line");index+;j=index; if(m=j)System.out.println("the illegal character "+allstrj);index+;j=index; class KeyTableString key;int code;public KeyTable(String key,int code)this.key=key;this.code=code;专心-专注-专业