這學期的課程設計,用java寫的詞法分析器

也看了網上大神們的作品,他們的思路都好清晰啊,我只能領悟了在開始自己寫了,大部分都加了註釋。。。

敲打

爲啥用java呢,c看着vc6.0和cb就頭疼啊

修改了一下,先在空格也可以判斷了。

代碼輸入

int a = 21 ;
int b = 22 ;
int c = 0 ;
c = a + b ;
a= a * b ;
int price = 22 ;


package parser;

import java.io.BufferedReader;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

import java.lang.reflect.Array;

import java.util.Arrays;

import java.util.Stack;

//輸入文本:

//int a=21;

//int b=22;

//int c=0;

//c=a+b;

//a=a*b;

//int price=22;

public class Parser {

Stack<Object> retain = new Stack<>();

Stack<Object> token = new Stack<>();

Stack<Object> cons = new Stack<>();

Stack<Object> oper = new Stack<>();

Stack<Object> bound = new Stack<>();

public int ch;//每次獲取的ascll字符

public int code = 0;//分類碼

/**  

* 1 基本字   保留字

* 2 標識符   自己的變量名

* 3 常數    

* 4 算符  

* 5 界符  

*/

// 保留字

String[] retainword = {"int","string","float","const","do",

"switch","for","if","else","while",

"break","new","return"};

// 操作符

int operator[] = {42,43,45,47,61};

// 界符

char delimiter[] = {',','{','}',';','(',')'};

// 單詞

StringBuffer strapp = new StringBuffer();

public static void main(String[] args) {

String[] delimiters = {"(",")",";",",","",""};

new Parser().scanner();

}

// 輸入的是否是字母

public boolean isLetter(){

if ((ch>64&&ch<91)||(ch>96&&ch<123)) {

return true;

}

return false;

}

// 輸入的是否是數字

public boolean isFigure(){

if (ch>47&&ch<58){

return true;

}

return false;

}

// 輸入的是否是空格

public boolean isSpace(int ch){

if (ch==32||(char)ch==' ') {

return true;

}

return false;

}

// 是否是操作符

public boolean isOperator(int ch){

for (int i : operator) {

if(ch==i){

oper.push((char)ch);

            return true;

}

}

return false;

}

// 是否是界符

public boolean isDelimiters(int ch){

for (char c : delimiter) {

if((char)ch==c){

bound.push((char)ch);

            return true;

}

}

return false;

}

// 單詞判斷

public int isRetainW(){

for (String string : retainword) {

if (strapp.toString().equals(string)) {

retain.push(strapp.toString());

return 1;

}else if(strapp.length() != 0){  

            if(strapp.charAt(0)>='0' && strapp.charAt(0)<='9'){  

            cons.push(strapp.toString());

                return 3;  

            }  

        }  

}

String a = strapp.toString();

// 如果拼接的字符串爲0的話就放棄這個字符串,因爲它是代碼中的空格

if(a.equals("")){

// System.out.println(a+"!!!");

return 0;

}

token.push(strapp.toString());

return 2;

}

// 字符串拼接

public void strAppend(char ch){

strapp.append(ch);

}

// 輸出結果

public void sysostr(){

code = isRetainW();

if (code!=0) {

System.out.println("("+code+","+strapp+")");

}

code = 0;

strapp.delete(0, strapp.length());

}

public void scanner(){

BufferedReader br;

try {

br = new BufferedReader(new FileReader("/Users/rqw1991/Downloads/dd.txt"));

// 讀入數據

while((ch=br.read())!=-1){

/**

* 

*/

// 是不是空格,不是空格繼續

if (!isSpace(ch)) {

// 是不是字母,是字母就開始進入字符串的拼接

if(isLetter()){

// 如果不是空格而且是字母或者數字的話就開始進行句柄的拼接

if((isLetter()||isFigure())&&(!isSpace(ch))){

strAppend((char)ch);

}

}else if(isFigure()==true&&(!isSpace(ch))){

strAppend((char)ch);

}else if(isFigure()&&(!isSpace(ch))){

strAppend((char)ch);

}

// else if(ch == 61){  

//                        if((strapp.length() != 0 )&& (strapp.charAt(0) == '=')){  

//                            strapp.append((char)ch);  

//                            System.out.println("("+4+",'"+strapp+"')");  

//                            strapp.delete(0, strapp.length());  

//                        }else{  

//                            strapp.append((char)ch);  

//                        }  

//                    }

else if(isDelimiters(ch)&&(!isSpace(ch))){  

                        sysostr();  

                        System.out.println("("+4+","+(char) ch+")");  

                    }

                    else if(isOperator(ch)&&(!isSpace(ch))){  

                        sysostr();  

                        System.out.println("("+5+","+(char) ch+")");  

                    }

}else{

sysostr();

}

}

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally {

int rsize = retain.size();

System.out.println("1:"+rsize);

for (int i = 0; i < rsize; i++) {

System.out.print(i+":"+retain.pop()+" ");

}

System.out.println();

int tsize = token.size();

System.out.println("2:"+token.size());

for (int i = 0; i < tsize; i++) {

System.out.print(i+":"+token.pop()+" ");

}

System.out.println();

int csize = cons.size();

System.out.println("3:"+cons.size());

for (int i = 0; i < csize; i++) {

System.out.print(i+":"+cons.pop()+" ");

}

System.out.println();

int osize = oper.size();

System.out.println("4:"+oper.size());

for (int i = 0; i < osize; i++) {

System.out.print(i+":"+oper.pop()+" ");

}

System.out.println();

int bsize = bound.size();

System.out.println("5:"+bound.size());

for (int i = 0; i < bsize; i++) {

System.out.print(i+":"+bound.pop()+" ");

}

}

}

}

package parser;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Stack;

//輸入文本:
//int a=21;
//int b=22;
//int c=0;
//c=a+b;
//a=a*b;
//int price=22;

public class Parser {
	Stack<Object> retain = new Stack<>();
	Stack<Object> token = new Stack<>();
	Stack<Object> cons = new Stack<>();
	Stack<Object> oper = new Stack<>();
	Stack<Object> bound = new Stack<>();
	
	
	public int ch;//每次獲取的ascll字符
	public int code = 0;//分類碼
	/**  
	 * 1 基本字   保留字
	 * 2 標識符   自己的變量名
	 * 3 常數    
	 * 4 算符  
	 * 5 界符  
	 */
	
//	保留字
	String[] retainword = {"int","string","float","const","do",
			"switch","for","if","else","while",
			"break","new","return"};
	
//	操作符
	int operator[] = {42,43,45,47,61};
	
//	界符
	char delimiter[] = {',','{','}',';','(',')'};
	
//	單詞
	StringBuffer strapp = new StringBuffer();
	public static void main(String[] args) {
		String[] delimiters = {"(",")",";",",","",""};
		new Parser().scanner();
		
	}
	
//	輸入的是否是字母
	public boolean isLetter(){
		if ((ch>64&&ch<91)||(ch>96&&ch<123)) {
			return true;
		}
		return false;
	}
	
//	輸入的是否是數字
	public boolean isFigure(){
		if (ch>47&&ch<58){
			return true;
		}
		return false;
	}
	
//	輸入的是否是空格
	public boolean isSpace(int ch){
		if (ch==32||(char)ch==' ') {
			return true;
		}
		return false;
	}
	
//	是否是操作符
	public boolean isOperator(int ch){
		for (int i : operator) {
			if(ch==i){
				oper.push((char)ch);
	            return true;
			}
		}
		return false;
	}
	
//	是否是界符
	public boolean isDelimiters(int ch){
		for (char c : delimiter) {
			if((char)ch==c){
				bound.push((char)ch);
	            return true;
			}
		}
		return false;
	}
	
//	單詞判斷
	public int isRetainW(){
		for (String string : retainword) {
			if (strapp.toString().equals(string)) {
				retain.push(strapp.toString());
				return 1;
			}else if(strapp.length() != 0){  
	            if(strapp.charAt(0)>='0' && strapp.charAt(0)<='9'){  
	            	cons.push(strapp.toString());
	                return 3;  
	            }  
	        }  
		}
		String a = strapp.toString();
//		如果拼接的字符串爲0的話就放棄這個字符串,因爲它是代碼中的空格
		if(a.equals("")){
//			System.out.println(a+"!!!");
			return 0;
		}
		token.push(strapp.toString());
		return 2;
	}
	
//	字符串拼接
	public void strAppend(char ch){
		strapp.append(ch);
	}
	
//	輸出結果
	public void sysostr(){
		code = isRetainW();
		if (code!=0) {
			System.out.println("("+code+","+strapp+")");	
		}
		code = 0;
		strapp.delete(0, strapp.length());
	}
	
	public void scanner(){
		BufferedReader br;
		try {
			br = new BufferedReader(new FileReader("/Users/rqw1991/Downloads/dd.txt"));
//			讀入數據
			while((ch=br.read())!=-1){
				/**
				 * 
				 */
//				是不是空格,不是空格繼續
				if (!isSpace(ch)) {
//					是不是字母,是字母就開始進入字符串的拼接
					if(isLetter()){
//						如果不是空格而且是字母或者數字的話就開始進行句柄的拼接
						if((isLetter()||isFigure())&&(!isSpace(ch))){
							strAppend((char)ch);
						}
					}else if(isFigure()==true&&(!isSpace(ch))){
						strAppend((char)ch);
					}else if(isFigure()&&(!isSpace(ch))){
						strAppend((char)ch);
					}
//					else if(ch == 61){  
//                        if((strapp.length() != 0 )&& (strapp.charAt(0) == '=')){  
//                            strapp.append((char)ch);  
//                            System.out.println("("+4+",'"+strapp+"')");  
//                            strapp.delete(0, strapp.length());  
//                        }else{  
//                            strapp.append((char)ch);  
//                        }  
//                    }
					else if(isDelimiters(ch)&&(!isSpace(ch))){  
                        sysostr();  
                        System.out.println("("+4+","+(char) ch+")");  
                    }
                    else if(isOperator(ch)&&(!isSpace(ch))){  
                        sysostr();  
                        System.out.println("("+5+","+(char) ch+")");  
                    }
				}else{
					sysostr();
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			int rsize = retain.size();
			System.out.println("1:"+rsize);
			for (int i = 0; i < rsize; i++) {
				System.out.print(i+":"+retain.pop()+" ");
			}
			System.out.println();
			int tsize = token.size();
			System.out.println("2:"+token.size());
			for (int i = 0; i < tsize; i++) {
				System.out.print(i+":"+token.pop()+" ");
			}
			System.out.println();
			int csize = cons.size();
			System.out.println("3:"+cons.size());
			for (int i = 0; i < csize; i++) {
				System.out.print(i+":"+cons.pop()+" ");
			}
			System.out.println();
			int osize = oper.size();
			System.out.println("4:"+oper.size());
			for (int i = 0; i < osize; i++) {
				System.out.print(i+":"+oper.pop()+" ");
			}
			System.out.println();
			int bsize = bound.size();
			System.out.println("5:"+bound.size());
			for (int i = 0; i < bsize; i++) {
				System.out.print(i+":"+bound.pop()+" ");
			}
		}
	}
}







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章