模拟一个DFA的执行 Java版

这学期在学编译原理,教材電子工业出版社《编译原理》(第四版),实验的第一个小任务就是这个,刚开始有点懵逼

其实就是从书上找一个DFA的例子实现一下就可以了

于是就找了书上41页的例子3.10实现一个Java版本的DFA

上代码!!

package dfn;

public class DFA {
	
	private String  content;
	private String[] status = {"q0","q1","q2"};
	
	private String startStatus;
	private String endStatus;
	
	
	public DFA(int start, int end) {
		startStatus = status[start];
		endStatus = status[end];
		System.out.println("开始状态:" + startStatus+ ", 结束状态:" + endStatus);
	}
	
	
	public void setContent(String content) {
		this.content = content;
	}

//	@SuppressWarnings("unused")
	public void result() {
		String status = getEndStrus(startStatus);
		if (status == null) {
			System.out.println("illegal input!");
		}if(status.equals(endStatus)){
			System.out.println("yes");
		}else {
			System.out.println("no");
		}
		
	}
	
	public String getEndStrus(String startStatus) {
		String status = startStatus;
		char[] tokens = getToken();
		System.out.print("状态机: " + status);
		for (int i = 0; i < tokens.length && status != null; i++) {
			char ch = tokens[i];
			String nextStatus = getNextStrus(status, ch);
			status = nextStatus;
			System.out.print("-->" + status);
		}
		System.out.println();
		return status;
	}
	
	public String getNextStrus(String start, char ch) {
		String nextStrus;
		switch (start) {
		case "q0":
			if(ch == 'a') {
				nextStrus = "q1";
			}
			else if(ch == 'b'){
				nextStrus = "q2";
			}else {
				nextStrus = null;
			}
			break;
		case "q1":
			if(ch == 'a' || ch == 'b') {
				nextStrus = "q1";
			}else {
				nextStrus = null;
			}
			break;
		case "q2":
			if(ch == 'a') {
				nextStrus = "q2";
			}
			else if(ch == 'b'){
				nextStrus = "q1";
			}else {
				nextStrus = null;
			}
			break;
		default:
			nextStrus =null;
			break;
		}
		return nextStrus;
	}
	
	public char[] getToken() {
		int count = 0;
		char[] tokens = new char[this.content.length()];
		for(int i = 0; i < this.content.length(); ++i) {
			char ch = this.content.charAt(i);
			if(ch != ' ' || ch != '\n') {
				tokens[count++] = ch;
			}
		}
		if(count != this.content.length()) {
			char[] arrayChar = new char[count];
			System.arraycopy(tokens, 0, arrayChar, 0, count);
			tokens = arrayChar;
		}
		return tokens;
	}
	
}
package dfn;

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		
		System.out.println("输入DFA开始状态和结束状态,一行一个:");   //输入0或1或2
		Scanner input = new Scanner(System.in);
		int start = input.nextInt();
		int end = input.nextInt();
		input.nextLine();
		while(true) {
			System.out.println("输入要分析的字符串:");
			String content = input.nextLine();
			DFA dfa = new DFA(start, end);
			dfa.setContent(content);
			dfa.result();
		}
	}
}

测试数据及结果

当输入字符不符合要求时,会显示非法输入

 

猜你喜欢

转载自blog.csdn.net/godelgnis/article/details/83218389