詞法分析器Java

餘生與你發表於2017-11-05

本文章是一篇關於詞法分析的程式程式碼。

本程式碼還並不完善,只是一雛形還有許多需要改進的地方。

僅供參考:如有問題可發郵件詢問 lilongsha@163.com

詞法分析主程式:Wordanalysis.java

package com.lfsf.lls;

import java.util.Scanner;

public class Wordanalysis {
	@SuppressWarnings("resource")
	public static void main(String args[]) {
		//輸入程式段
		System.out.println("請輸入程式程式碼段:");
		Scanner sc = new Scanner(System.in);
		String str1 = sc.nextLine();
		String temp = "";
		String temp1 = "";
		int i;
		int start = 0;
		//遍歷輸入的程式段對其進行判斷
		for (i = 0; i < str1.length(); i++) {
			temp = str1.substring(i, i + 1);
			if (Operator.isOperator(temp)) {
				start = i + 1;
				Keyword.isKeyword(temp1);
			} else {
				temp1 = str1.substring(start, i);
			}
			if (Limitword.isOperator(temp)) {
				start = i + 1;
				Keyword.isKeyword(temp1);
			} else {
				temp1 = str1.substring(start, i + 1);
			}
		}
	}
}


詞法分析關鍵字類:Keyword.java

package com.lfsf.lls;

public class Keyword {
	//關鍵字陣列
	static private String word[] = {"switch","break","if","then","else","while","write","read","do","int","const","char","float","double","for","String","static","public","private","boolean"};
	
	public String[] getWord() {
		return word;
	}
	//判斷是否為關鍵字陣列
	static public boolean isKeyword(String paramater){
		for(String value:word){
			if(paramater.equals(value)){
				System.out.println("<" + "\"" + paramater + "\"" + "\t關鍵字" + ">");
				return true;
			}
		}
		System.out.println("<" + "\"" + paramater + "\"" + "\t非關鍵字" + ">");
		return false;
	}
	
	
}


詞法分析運算子類:Operator.java

package com.lfsf.lls;

public class Operator {
	//運算子陣列
	static private String word[] = {"+","-","*","/","%","<",">","="};
	
	public String[] getWord() {
		return word;
	}
	//判斷是否為運算子方法
	static public boolean isOperator(String paramater){
		for(String value:word){
			if(paramater.equals(value)){
				System.out.println("<" + "\"" + paramater + "\"" + "\t運算子" + ">");
				return true;
			}
		}
		return false;
	}
	
}


詞法分析邊界符類:Limitword.java

package com.lfsf.lls;

public class Limitword {
	//邊界符陣列
	static private String word[] = {"(",")","[","]","{","}",";"," "};
	
	public String[] getWord() {
		return word;
	}
	//判斷是否為邊界符方法
	static public boolean isOperator(String paramater){
		for(String value:word){
			if(paramater.equals(value)){
				//如果是空格則不進行輸出
				if(" ".equals(paramater) || "".equals(paramater)) {
					return true;
				}
				System.out.println("<" + "\"" + paramater + "\"" + "\t邊界符" + ">");
				return true;
			}
		}
		return false;
	}
}

相關文章