模拟⼀个DFA的执⾏Java版
想了解更多内容,移步⾄
==========================2021.12.22 更新===================================
整理了⼀下代码,同步到了gitee
--------------------------------------------------分割线---------------------------------------------------------------------
这学期在学编译原理,教材電⼦⼯业出版社《编译原理》(第四版),实验的第⼀个⼩任务就是这个,刚开始有点懵逼
其实就是从书上⼀个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) {
}
// @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);
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";
java switch case string}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 t.length()];
for(int i = 0; i < t.length(); ++i) {
char ch = t.charAt(i);
if(ch != ' ' || ch != '\n') {
tokens[count++] = ch;
}
}
if(count != t.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 = Int();
int end = Int();
while(true) {
System.out.println("输⼊要分析的字符串:");
String content = Line();
DFA dfa = new DFA(start, end);
dfa.setContent(content);
}
}
}
测试数据及结果
当输⼊字符不符合要求时,会显⽰⾮法输⼊
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论