먼저 다음과 같이 분석하려는 코드 세그먼트를 살펴 보겠습니다.
출력 결과는 다음과 같습니다.
출력 결과 (a) .png
출력 결과 (b) .png
출력 결과 (c) .png
브래킷에는 이진 표현이 있습니다. (단어 카테고리 인코딩, 단어 위치 번호)
코드는 다음과 같습니다.
패키지 yue.lexicalAnalyzer; import java.io.*;/** 메인 프로그램*/public class main {public static void main (String [] args)은 ioexception {Lexer Lexer = new Lexer (); Lexer.printtoken (); Lexer.printsymbolstable (); }} package yue.lexicalAnalyzer; import java.io.*; import java.util.*;/**어휘 분석 및 출력*/public class lexer {/*레코드 라인 번호*/public static int line = 1; /*최신 읽기 문자 저장*/ char 문자 = ''; /*예약 단어*/ hashtable <문자열, 키워드> 키워드 = new Hashtable <String, keyword> (); /*토큰 시퀀스*/ private arraylist <Token> Tokens = new ArrayList <Token> (); /*기호 테이블*/ private arraylist <Symbol> symtable = new ArrayList <Symbol> (); /*파일 읽기 변수*/ bufferedReader reader = null; /*파일의 끝이 현재 읽는지 여부를 저장*/ private boolean isend = false; /*파일의 끝이 읽는지*/ public boolean getReaderstate () {return this.isend; }/*인쇄 토큰 시퀀스*/public void printtoken ()는 ioexception {filewriter writer = new FileWriter ( "e : //lex.txt"); System.out.println ( "어휘 분석 결과는 다음과 같습니다."); System.out.print ( "du yue-2015220201031/r/n/n"); Writer.write ( "du yue-2015220201031/r/n/r/n"); while (getReaderstate () == false) {token tok = scan (); String str = "line" + tok.line + "/t (" + tok.tag + "," + tok.pos + ")/t/t" + tok.name + ":" + tok.tostring () + "/r/n"; Writer.write (str); System.out.print (str); } writer.flush (); }/*인쇄 기호 테이블*/public void printsymbolstable ()는 ioexception {filewriter writer = new filewriter ( "e : //symtab1.txt"); System.out.print ( "/r/n/r/n 기호 테이블/r/n"); System.out.print ( "번호/T 라인 번호/t 이름/r/n"); writer.write ( "기호 테이블/r/n"); writer.write ( "숫자" + "/t 줄 번호" + "/t name/r/n"); 반복자 <cympart> e = symtable.iterator (); while (e.hasnext ()) {Symbol Symbol = e.next (); 문자열 desc = symbol.pos + "/t" + symbol.line + "/t" + symbol.toString (); System.out.print (desc + "/r/n"); Writer.write (desc + "/r/n"); } writer.flush (); }/*인쇄 오류*/public void printerror (Token Tok)는 ioexception {filewriter writer = new filewriter ( "e : //error.txt"); System.out.print ( "/r/n/r/n 오류 사전 어휘는 다음과 같습니다 :/r/n"); Writer.write ( "오류 사전 촬영법은 다음과 같습니다 : /r /n"); String str = "line" + tok.line + "/t (" + tok.tag + "," + tok.pos + ")/t/t" + tok.name + ":" + tok.tostring () + "/r/n"; Writer.write (str); } /*예약 된 단어 추가* / void Reserve (키워드 w) {keywords.put (w.lexme, w); } public lexer () {/*파일 읽기 변수 초기화*/try {reader = new bufferedReader (new FilerEader ( "e : //input.txt")); } catch (ioexception e) {System.out.print (e); } /*예약 된 단어 추가* / this.reserve (keyword.begin); this.reserve (keyword.end); this.reserve (keyword.integer); this.reserve (keyword.function); this.reserve (keyword.Read); this.reserve (keyword.write); this.reserve (keyword.aif); this.reserve (keyword.athen); this.reserve (keyword.aelse); } /*ar if (int) 문자 == 0xffff) {this.isend = true; }} /*일치하는지 판단* / public boolean readch (char ch)는 ioexception {readch (); if (this.character! = ch) {return false; } this.character = ''; 진실을 반환하십시오. } /*숫자의 인식* / public boolean isdigit ()는 ioexception {if (arribute.isdigit (aracter)) {int value = 0; while (charac readch (); } num n = new num (값); n.line = 선; Tokens.add (n); 진실을 반환하십시오. } 그렇지 않으면 거짓을 반환합니다. } /*예약 된 단어 및 식별자의 인식* / public boolean isletter ()는 ioException {if (arribute.isletter (문자)) {StringBuffer sb = new StringBuffer (); /*먼저 전체 분할을 얻습니다*/ while (ar readch (); } /*예약 된 단어인지 식별자인지 판단* / 문자열 s = sb.toString (); 키워드 w = keywords.get (s); /*예약 된 단어 인 경우 w는 비어 있지 않아야합니다*/ if (w! = null) {w.line = line; tokens.add (w); } else { /* 그렇지 않으면 식별자입니다. 여기에 식별자 번호* / 기호를 기록하는 추가 설명이 있습니다. 기호 표시 = sy; // 기존 식별자를 표시하는 데 사용됩니다. boolean isrepeat = false; sy.line = line; for (기호 i : symtable) {if (sy.toString (). Equals (i.toString ()) {mark = i; isrepeat = true; }} if (! isrepeat) {sy.pos = symtable.size () + 1; Symtable.add (Sy); } else if (isrepeat) {sy.pos = mark.pos; } tokens.add (sy); } true를 반환합니다. } 그렇지 않으면 거짓을 반환합니다. } /*기호 인식* / public boolean issign ()는 ioexception {switch (문자) {case '#': readch (); allend.allend.line = line; tokens.add (allend.allend); 진실을 반환하십시오. case '/r': if (readch ( '/n')) {readch (); lineend.lineend.line = line; tokens.add (lineend.lineend); 라인 ++; 진실을 반환하십시오. } case '(': readch (); delimiter.lpar.line = line; tokens.add (delimiter.lpar); return true; case ')': readch (); delimiter.rpar.line = line; tokens.add (delimiter.rpar); 진실을 반환하십시오. case ';': readch (); delimiter.sem.line = line; tokens.add (delimiter.sem); 진실을 반환하십시오. CASE '+': readch (); calcword.add.line = line; tokens.add (calcword.add); 진실을 반환하십시오. case '-': readch (); calcword.sub.line = line; tokens.add (calcword.sub); 진실을 반환하십시오. CASE '*': readch (); calcword.mul.line = line; tokens.add (calcword.mul); 진실을 반환하십시오. case '/': readch (); calcword.div.line = line; tokens.add (calcword.div); 진실을 반환하십시오. case ':': if (readch ( '=')) {readch (); calcword.assign.line = line; tokens.add (calcword.assign); 진실을 반환하십시오. } 부서지다; case '>': if (readch ( '=')) {readch (); calcword.ge.line = line; tokens.add (calcword.ge); 진실을 반환하십시오. } 부서지다; case '<': if (readch ( '=')) {readch (); calcword.le.line = line; tokens.add (calcword.le); 진실을 반환하십시오. } 부서지다; case '!': if (readch ( '=')) {readch (); calcword.ne.line = line; tokens.add (calcword.ne); 진실을 반환하십시오. } 부서지다; } false를 반환합니다. } /*다음은 키워드, 식별자 및 기타 정보를 분할하기 시작합니다* / public token scan ()는 ioexception {Token Tok; while (character == '') readch (); if (isdigit () || issign () || isletter ()) {tok = tokens.get (tokens.size () -1); } else {tok = 새로운 토큰 (문자); 프린터러 (토크); } 리턴 토크; }} package yue.lexicalAnalyzer;/ * * 토큰 부모 클래스 */public class token {public final int tag; 공개 int line = 1; 공개 문자열 이름 = ""; 공개 int pos = 0; 공개 토큰 (int t) {this.tag = t; } public String toString () {return "" + (char) 태그; }} package yue.lexicalAnalyzer;/** 단어 카테고리 할당*/public class tag {public final static int begin = 1, // 예약 된 단어 end = 2, // 예약 된 단어 integer = 3, // 예약 된 단어 함수 = 4, // 예약 된 단어 읽기 = 5, // 예약 된 단어 if = 7, // 예약 된 단어 = 8, // 예약 된 단어 = 9 // identifier constant = 12, // constant add = 13, // 연산자 "+"sub = 14, // operator "-"mul = 15, // 연산자 "*"div = 16, // operator "/"le = 18, // 연산자 "<="ge = 19, // 연산자 "> = 20, // operator" // 연산자 "("rpar = 25, // operator ")"sem = 26, // 연산자 ";" line_end = 27, // 연산자 All_end = 28; // 연산자 "#"} package yue.lexicalAnalyzer;/*** 예약 된 단어*/public class 키워드는 토큰 {public String lexme = ""; 공개 키워드 (문자열 S, int t) {super (t); this.lexme = s; this.name = "예약 된 단어"; } public String toString () {return this.Lexme; } public static final 키워드 시작 = 새 키워드 ( "시작", tag.begin), end = new 키워드 ( "End", tag.end), integer = new Keyword ( "Integer", tag.integer), function = new Keyword ( "function", tag.functer), read = new Keyword ( "읽기", 태그 ", 쓰기) 키워드 ( "if", tag.if), athen = new Keyword ( "way", tag.then), aelse = new 키워드 ( "else", tag.else);} package yue.lexicalAnalyzer;/** 식별자*/public class 기호는 토큰 {public String lexme = ""; 공개 기호 (문자열 s) {super (tag.symbol); this.lexme = s; this.name = "식별자"; } public String toString () {return this.Lexme; }} package yue.lexicalAnalyzer;/*** 연산자*/public class calcword 확장 토큰 {public String lexme = ""; public calcword (문자열 s, int t) {super (t); this.lexme = s; this.name = "연산자"; } public String toString () {return this.Lexme; } public static final calcword add = new calcword ( "+", tag.add), sub = new calcword ( "-", tag.sub), mul = new calcword ( "*", tag.mul), div = new calcword ( "/", tag.div), le = new calcword ( "<=", tag.le), ge = "> =", ne = ne = " tag.ne), 할당 = new calcword ( ": =", tag.assign);} package yue.lexicalAnalyzer;/*** 경계 기호*/public class delimiter 확장 토큰 {public String lexme = ""; public delimiter (문자열 s, int t) {super (t); this.lexme = s; this.name = "경계 기호"; } public String toString () {return this.Lexme; } public static final delimiter lpar = new Delimiter ( "(", tag.lpar), rpar = new Delimiter ( ")", tag.rpar), sem = new Delimiter ( ";", tag.sem);} 패키지 yue.lexicalAnalyzer;/** Constant*/Public Class Num은 토큰 {public final int value; public num (int v) {super (tag.constant); this.value = v; this.name = "constant"; } public String toString () {return "" + value; }} package yue.lexicalAnalyzer;/*** 라인 문자 끝*/public class lineend는 토큰 {public String lexme = ""; 공개 라인 엔드 (문자열 s) {super (tag.line_end); this.lexme = s; this.name = "라인 문자 끝"; } public String toString () {return this.Lexme; } public static final lineend lineend = new Lineend ( "/r/n");} package yue.lexicalAnalyzer;/*** Ending Char Public Allend (String S) {Super (tag.all_end); this.lexme = s; this.name = "end 문자"; } public String toString () {return this.Lexme; } public static final allend allend = new Allend ( "#");}요약
이 기사의 전체 내용으로 잠을 자려고합니다. 이 기사의 내용이 귀하의 연구 나 업무에 도움이되기를 바랍니다. 궁금한 점이 있으면 의사 소통을 위해 메시지를 남길 수 있습니다.