當前位置:首頁 » 編程語言 » 詞法分析java

詞法分析java

發布時間: 2023-03-05 07:44:04

1. 如何用java編寫詞法分析器程序

我也做過這個作業

packagesource;

importjava.util.LinkedList;

publicclassLexicalAnalysis
{
//私有變數聲明
privateLinkedList<Word>optr=newLinkedList<Word>();
privateStringexp;
//詞法分析
publicLinkedList<Word>lexical_analysis(Stringexp)
{
charch='';//當前文件指針內容
intindex=0;//文件指針
StringBufferstrToken=newStringBuffer("");
//掃描處理字元串
while(true)
{
ch=exp.charAt(index);
index++;
//標識符(字母開頭,數字或字元組成)
if(Character.isLetter(ch))
{
while(Character.isLetter(ch)||Character.isDigit(ch))
{
strToken.append(ch);
ch=exp.charAt(index);
index++;
}
index--;
Stringstr=strToken.toString();
if(str.equals("if"))
optr.add(newWord(str,13));
elseif(str.equals("else"))
optr.add(newWord(str,14));
elseif(str.equals("then"))
optr.add(newWord(str,15));
else
optr.add(newWord(str,26));
}
//數字
elseif(Character.isDigit(ch))
{
while(Character.isDigit(ch))
{
strToken.append(ch);
ch=exp.charAt(index);
index++;
}
index--;
optr.add(newWord(strToken.toString(),26));
}
//加號或自加
elseif(ch=='+')
{
ch=exp.charAt(index);
index++;
if(ch=='+')
optr.add(newWord("++",21));
elseif(ch=='=')
optr.add(newWord("+=",16));
else
{
index--;
optr.add(newWord("+",19));
}
}
//加號或自加
elseif(ch=='-')
{
ch=exp.charAt(index);
index++;
if(ch=='-')
optr.add(newWord("--",21));
elseif(ch=='=')
optr.add(newWord("-=",16));
else
{
index--;
optr.add(newWord("-",19));
}
}
//乘法或乘冪
elseif(ch=='*')
{
ch=exp.charAt(index);
index++;
if(ch=='*')
optr.add(newWord("**",20));
elseif(ch=='=')
optr.add(newWord("*=",16));
else
{
index--;
optr.add(newWord("*",20));
}
}
//除法或注釋
elseif(ch=='/')
{
ch=exp.charAt(index);
index++;
//多行注釋
if(ch=='*')
{
while(true)
{
ch=exp.charAt(index);
index++;
if(ch=='*')
{
ch=exp.charAt(index);
index++;
if(ch=='/')break;
elseif(ch==' ')
{
exp=Input.newLine();
index=0;
ch=exp.charAt(index);
index++;
}
elseindex--;
}
elseif(ch=='#')
{
inttIndex=index-1;
if(exp.length()>tIndex+9)
{
Stringend=exp.substring(tIndex,tIndex+9);
if(end.equals("#?e_N_d?#"))break;
}
else
{
System.out.println("非法符號'#'後的語句忽略!");
exp=Input.newLine();
index=0;
break;
}
}
elseif(ch==' ')
{
exp=Input.newLine();
index=0;
}
}
}
//單行注釋
elseif(ch=='/')
break;
elseif(ch=='=')
optr.add(newWord("/=",16));
else
{
index--;
optr.add(newWord("/",20));
}
}
//大於或大於等於或右移
elseif(ch=='>')
{
ch=exp.charAt(index);
index++;
if(ch=='=')
optr.add(newWord(">=",18));
elseif(ch=='>')
optr.add(newWord(">>",20));
else
{
index--;
optr.add(newWord(">",18));
}
}
//小於或小於等於或左移
elseif(ch=='<')
{
ch=exp.charAt(index);
index++;
if(ch=='=')
optr.add(newWord("<=",18));
elseif(ch=='<')
optr.add(newWord("<<",20));
else
{
index--;
optr.add(newWord("<",18));
}
}
//賦值或等於
elseif(ch=='=')
{
ch=exp.charAt(index);
index++;
if(ch=='=')
optr.add(newWord("==",18));
else
{
index--;
optr.add(newWord("=",16));
}
}
//或運算按位或
elseif(ch=='|')
{
ch=exp.charAt(index);
index++;
if(ch=='|')
optr.add(newWord("||",17));
else
{
index--;
optr.add(newWord("|",20));
}
}
//與運算
elseif(ch=='&')
{
ch=exp.charAt(index);
index++;
if(ch=='&')
optr.add(newWord("&&",17));
else
{
index--;
optr.add(newWord("&",20));
}
}
//非運算或不等於
elseif(ch=='!')
{
ch=exp.charAt(index);
index++;
if(ch=='=')
optr.add(newWord("!=",18));
else
{
index--;
optr.add(newWord("!",21));
}
}
//按位亦或
elseif(ch=='^')
optr.add(newWord("^",20));
//取模運算
elseif(ch=='%')
optr.add(newWord("%",20));
//左括弧
elseif(ch=='(')
optr.add(newWord("(",22));
//右括弧
elseif(ch==')')
optr.add(newWord(")",23));
//左大括弧
elseif(ch=='{')
optr.add(newWord("{",24));
//右大括弧
elseif(ch=='}')
optr.add(newWord("}",25));
//結束掃描標志為:#?e_N_d?#
elseif(ch==' ')
{
break;
}
elseif(ch=='#')
{
inttIndex=index-1;
if(exp.length()>tIndex+9)
{
Stringend=exp.substring(tIndex,tIndex+9);
if(end.equals("#?e_N_d?#"))
{
optr.add(newWord("#",27));
break;
}
}
else
{
System.out.println("非法符號'#'後的語句忽略!");
optr.add(newWord("#",27));
break;
}
}
//清空掃描串
strToken.setLength(0);
}
returnoptr;
}
}

2. 請用JAVA編程輸入一個語句進行詞法分析

我最近正在學編譯原理,我有c語言實現的詞法分析程序,不知可不可以,識別的是TEST語言的單詞。

#include<stdio.h>

#include<ctype.h>

#include<string.h>


#define keywordSum 8


char * keyword[keywordSum] = {"do", "else", "for", "if", "int", "read", "while", "write"};

char singleword[50] = "+-*(){};,:";

char doubleword[10] = "><=!|&";


char Scanin[300], Scanout[300];

FILE * fin, * fout;


int binaryFind(int low, int high, char * c1, char ** c2) {


int mid;

if(low > high) return -1;

mid = (low+high)/2;

if(strcmp(c1, c2[mid]) == 0) return mid;

else if(strcmp(c1, c2[mid]) > 0) return binaryFind(mid+1, high, c1, c2);

else return binaryFind(low, mid-1, c1, c2);

}


int TESTscan() {


char ch, token[40];

int es = 0, j, n;


printf("請輸入源文件名(包括路徑):");

scanf("%s", Scanin);

printf("請輸入詞法分析輸出文件名(包括路徑):");

scanf("%s", Scanout);


if((fin=fopen(Scanin, "r")) == NULL) {

printf(" 打開詞法分析輸入文件出錯! ");

return 1;

}

if((fout=fopen(Scanout, "w")) == NULL) {

printf(" 創建詞法分析輸出文件出錯! ");

return 2;

}


// printf("%c", getc(fin));


ch = getc(fin);


while(ch != EOF) {


while(ch==' ' || ch==' ' || ch==' ') {

ch = getc(fin);

}


if(isalpha(ch)) { //標識符


token[0] = ch;

j = 1;

ch = getc(fin);

while(isalnum(ch)) { //判斷當前字元是否是字母或數字

token[j++] = ch;

ch = getc(fin);

}

token[j] = '';

// printf("%s", token);

n = binaryFind(0, keywordSum-1, token, keyword);

if(n < 0 ) {

fprintf(fout, "%s %s ", "ID", token);

} else {

fprintf(fout, "%s %s ", token, token);

}


} else if(isdigit(ch)) { //數字


token[0] = ch;

j = 1;

ch = getc(fin);

while(isdigit(ch)) {

token[j++] = ch;

ch = getc(fin);

}

token[j] = '';


fprintf(fout, "%s %s ", "NUM", token);


} else if(strchr(singleword, ch) > 0) { //singleword


token[0] = ch;

token[1] = '';

ch = getc(fin);


fprintf(fout, "%s %s ", token, token);


} else if(strchr(doubleword, ch) > 0) { //doubleword


token[0] = ch;

ch = getc(fin);


if(ch=='=' && (token[0]=='>'||token[0]=='<' || token[0] == '!')) {

token[1] = ch;

token[2] = '';

ch = getc(fin);

} else if((ch=='&')||(ch=='|')||(ch=='=') && ch==token[0]) {

token[1] = ch;

token[2] = '';

ch = getc(fin);

} else {

token[1] = '';

}


fprintf(fout, "%s %s ", token, token);


} else if(ch == '/') { //注釋


ch = getc(fin);


if(ch == '*') {

char ch1;

ch1 = getc(fin);

do {

ch = ch1;

ch1 = getc(fin);

} while((ch!='*'||ch1!='/') && ch1!=EOF);


ch = getc(fin);


} else {

token[0] = '/';

token[1] = '';

fprintf(fout, "%s %s ", token, token);

}


} else {


token[0] = ch;

token[1] = '';

ch = getc(fin);

es = 3;


fprintf(fout, "%s %s ", "ERROR", token);

}

}


fclose(fin);

fclose(fout);


return es;


}


void main() {


int es = 0;

es = TESTscan();

if(es > 0) {

printf("詞法分析有錯, 編譯停止! ");

} else {

printf("詞法分析成功! ");

}


}

3. 怎麼用java寫一個詞法分析器

首先看下我們要分析的代碼段如下:

輸出結果(c).PNG

括弧里是一個二元式:(單詞類別編碼,單詞位置編號)

代碼如下:

?

1234567891011121314package Yue.LexicalAnalyzer;import java.io.*;/** 主程序*/public class Main {public static void main(String[] args) throws 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 character = ' ';/*保留字*/Hashtable<String, KeyWord> keywords = new Hashtable<String, KeyWord>();/*token序列*/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;}/*列印tokens序列*/public void printToken() throws IOException {FileWriter writer = new FileWriter("E:\lex.txt");System.out.println("詞法分析結果如下:");System.out.print("杜悅-2015220201031 ");writer.write("杜悅-2015220201031 ");while (getReaderState() == false) {Token tok = scan();String str = "line " + tok.line + " (" + tok.tag + "," + tok.pos + ") "+ tok.name + ": " + tok.toString() + " ";writer.write(str);System.out.print(str);}writer.flush();}/*列印符號表*/public void printSymbolsTable() throws IOException {FileWriter writer = new FileWriter("E:\symtab1.txt");System.out.print(" 符號表 ");System.out.print("編號 行號 名稱 ");writer.write("符號表 ");writer.write("編號 " + " 行號 " + " 名稱 ");Iterator<Symbol> e = symtable.iterator();while (e.hasNext()) {Symbol symbol = e.next();String desc = symbol.pos + " " + symbol.line + " " + symbol.toString();System.out.print(desc + " ");writer.write(desc + " ");}writer.flush();}/*列印錯誤*/public void printError(Token tok) throws IOException{FileWriter writer = new FileWriter("E:\error.txt");System.out.print(" 錯誤詞法如下: ");writer.write("錯誤詞法如下: ");String str = "line " + tok.line + " (" + tok.tag + "," + tok.pos + ") "+ tok.name + ": " + tok.toString() + " ";writer.write(str);}/*添加保留字*/void reserve(KeyWord w) {keywords.put(w.lexme, w);}public Lexer() {/*初始化讀取文件變數*/try {reader = new BufferedReader(new FileReader("E:\輸入.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);}/*按字元讀*/public void readch() throws IOException {character = (char) reader.read();if ((int) character == 0xffff) {this.isEnd = true;}}/*判斷是否匹配*/public Boolean readch(char ch) throws IOException {readch();if (this.character != ch) {return false;}this.character = ' ';return true;}/*數字的識別*/public Boolean isDigit() throws IOException {if (Character.isDigit(character)) {int value = 0;while (Character.isDigit(character)) {value = 10 * value + Character.digit(character, 10);readch();}Num n = new Num(value);n.line = line;tokens.add(n);return true;} elsereturn false;}/*保留字、標識符的識別*/public Boolean isLetter() throws IOException {if (Character.isLetter(character)) {StringBuffer sb = new StringBuffer();/*首先得到整個的一個分割*/while (Character.isLetterOrDigit(character)) {sb.append(character);readch();}/*判斷是保留字還是標識符*/String s = sb.toString();KeyWord w = keywords.get(s);/*如果是保留字的話,w不應該是空的*/if (w != null) {w.line = line;tokens.add(w);} else {/*否則就是標識符,此處多出記錄標識符編號的語句*/Symbol sy = new Symbol(s);Symbol mark = sy; //用於標記已存在標識符Boolean isRepeat = false;sy.line = line;for (Symbol 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);}return true;} elsereturn false;}/*符號的識別*/public Boolean isSign() throws IOException {switch (character) {case '#':readch();AllEnd.allEnd.line = line;tokens.add(AllEnd.allEnd);return true;case ' ':if (readch(' ')) {readch();LineEnd.lineEnd.line = line;tokens.add(LineEnd.lineEnd);line++;return true;}case '(':readch();Delimiter.lpar.line = line;tokens.add(Delimiter.lpar);return true;case ')':readch();Delimiter.rpar.line = line;tokens.add(Delimiter.rpar);return true;case ';':readch();Delimiter.sem.line = line;tokens.add(Delimiter.sem);return true;case '+':readch();CalcWord.add.line = line;tokens.add(CalcWord.add);return true;case '-':readch();CalcWord.sub.line = line;tokens.add(CalcWord.sub);return true;case '*':readch();CalcWord.mul.line = line;tokens.add(CalcWord.mul);return true;case '/':readch();CalcWord.div.line = line;tokens.add(CalcWord.div);return true;case ':':if (readch('=')) {readch();CalcWord.assign.line = line;tokens.add(CalcWord.assign);return true;}break;case '>':if (readch('=')) {readch();CalcWord.ge.line = line;tokens.add(CalcWord.ge);return true;}break;case '<':if (readch('=')) {readch();CalcWord.le.line = line;tokens.add(CalcWord.le);return true;}break;case '!':if (readch('=')) {readch();CalcWord.ne.line = line;tokens.add(CalcWord.ne);return true;}break;}return false;}/*下面開始分割關鍵字,標識符等信息*/public Token scan() throws IOException {Token tok;while (character == ' ')readch();if (isDigit() || isSign() || isLetter()) {tok = tokens.get(tokens.size() - 1);} else {tok = new Token(character);printError(tok);}return tok;}}

4. 編譯原理課程設計詞法分析器設計(java實現)

參考答案 永遠對生活充滿希望,對於困境與磨難,微笑面對。

5. 關於java編譯器中詞法分析,語法分析,語義分析

請採納

6. Java代碼到底是如何編譯成機器指令的

編譯器把一種語言規范轉化為另一種語言規范的這個過程需要哪些步驟?回答這個問題需要參照《編譯原理》,總結過程如下:

        1)詞法分析:讀取源代碼,一個位元組一個位元組的讀進來,找出這些詞法中我們定義的語言關鍵詞如:if、else、while等,識別哪些if是合法的哪些是不合法的。這個步驟就是詞法分析過程。

        詞法分析的結果:就是從源代碼中找出了一些規范化的token流,就像人類語言中,給你一句話你要分辨出哪些是一個詞語,哪些是標點符號,哪些是動詞,哪些是名詞。

        2)語法分析:就是對詞法分析中得到的token流進行語法分析,這一步就是檢查這些關鍵片語合在一起是不是符合Java語言規范。如if的後面是不是緊跟著一個布爾型判斷表達式。

        語法分析的結果:就是形成一個符合Java語言規定的抽象語法樹,抽象語法樹是一個結構化的語法表達形式,它的作用是把語言的主要詞法用一個結構化的形式組織在一起。這棵語法樹可以被後面按照新的規則再重新組織。

        3)語義分析:語法分析完成之後也就不存在語法問題了,語義分析的主要工作就是把一些難懂的,復雜的語法轉化成更簡單的語法。就如難懂的文言文轉化為大家都懂的百話文,或者是注釋一下一些不懂的成語。

        語義分析結果:就是將復雜的語法轉化為簡單的語法,對應到Java就是將foreach轉化為for循環,還有一些注釋等。最後生成一棵抽象的語法樹,這棵語法樹也就更接近目標語言的語法規則。

        4)位元組碼生成:將會根據經過注釋的抽象語法樹生成位元組碼,也就是將一個數據結構轉化為另外一個數據結構。就像將所有的中文詞語翻譯成英文單詞後按照英文語法組裝文英文語句。代碼生成器的結果就是生成符合java虛擬機規范的位元組碼。

熱點內容
sqlserver連接驅動 發布:2024-05-06 00:33:34 瀏覽:645
存儲開銷 發布:2024-05-06 00:13:38 瀏覽:953
伺服器怎麼盈利 發布:2024-05-05 23:56:16 瀏覽:941
java網站培訓學校 發布:2024-05-05 23:43:11 瀏覽:40
淘寶搜索演算法 發布:2024-05-05 23:37:07 瀏覽:998
sqlwhencasethen 發布:2024-05-05 23:27:51 瀏覽:641
模架編程軟體 發布:2024-05-05 23:26:54 瀏覽:483
存儲過程異常 發布:2024-05-05 23:24:03 瀏覽:399
winxp訪問不了win7 發布:2024-05-05 23:05:23 瀏覽:734
演算法牛 發布:2024-05-05 22:43:40 瀏覽:720