/* 时间:2015年3月18日20:27:41 目的:DFA的实现,通过双重switch语句实现DFA 条件:因为本程序中使用了输入输出流,需要在E:/data.txt,建立该文件, 其中的内容为: 1 2 3 4 5 6 7 8 9 15
*/ import java.io.*; import java.util.*;
public class TestDFA { public static void main(String[] args) { FileReader fr = null; BufferedReader br = null; //Set<Integer> set0 = new HashSet<Integer>(); // set0.add(0);set0.add(3);set0.add(6);set0.add(9); // Set<Integer> set1 = new HashSet<Integer>(); //set1.add(1);set1.add(4);set1.add(7); //Set<Integer> set2 = new HashSet<Integer>(); //set2.add(2);set2.add(5);set2.add(8); char state = 'S';//初始状态 char ch; int index = 0; try { fr = new FileReader("E:/data.txt"); br = new BufferedReader(fr); String str = null; while ((str = br.readLine()) != null) { /* 保证每次处理每一行时最开始的情况,也就是原始状况 */ state = 'S'; index = 0; while (index<str.length()) { ch = str.charAt(index); switch (state) { case 'S' : switch ((ch-'0')%3){ case 0: state = 'A'; break; case 1: state = 'B'; break; case 2: state = 'C'; break; default : break; } break; case 'A' : switch ((ch-'0')%3) { case 0: state = 'A'; break; case 1: state = 'B'; break; case 2: state = 'C'; break; default : break; } break; case 'B' : switch ((ch-'0')%3) { case 0: state = 'B'; break; case 1: state = 'C'; break; case 2: state = 'A'; break; default : break; } break; case 'C' : switch ((ch-'0')%3) { case 0: state = 'C'; break; case 1: state = 'A'; break; case 2: state = 'B'; break; default : break; } break; default : break;
} index ++;//索引要自加 } switch (state) { case 'A': System.out.println("被3整除"); break; case 'B': System.out.println("被3整除余1"); break; case 'C': System.out.println("被3整除余2"); break; } } } catch (FileNotFoundException e) { System.out.println("文件未找到"); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { br.close(); fr.close(); } catch (IOException e) { e.printStackTrace(); } } } } /*
E:\java\GUI>javac TestDFA.java
E:\java\GUI>java TestDFA 被3整除余1 被3整除余2 被3整除 被3整除余1 被3整除余2 被3整除 被3整除余1 被3整除余2 被3整除 被3整除
E:\java\GUI> */