我正在一个项目上,我的代码不起作用,不确定为什么。给定测试程序和通用类,我需要一个满足以下逻辑常规要求的程序:
L1:对于字母{a,b},所有包含奇数个a和恰好一个b的字符串。
测试输入:aabaaaa,aaabaaaa,aabaaaab,baaaaaa,aaaaabaa
应该是什么:
aabaaaa错误
aaabaaaa True
aabaaaab错误
baaaaaa错误
aaaaabaa True
程序输出: (真实,真实,真实,错误,真实)
我的测试程序:
import java.util.Scanner;
// Test Finite State Machine Class
public class TestFSML1
{
public static void main(String[] args){
String A = "ab";
int[][] ST = {{1,3,0},
{1,2,1},
{2,2,2},
{3,3,3}};
int[] AS = {0,0,1,0};
Scanner in = new Scanner(System.in);
String inString;
boolean accept1 = false;
FSM FSM1 = new FSM(A, ST, AS);
// Input string is command line parameter
System.out.println(" Input Accepted:");
for(int i=0;i<args.length;i++) {
inString = args[i];
accept1 = FSM1.validString(inString);
System.out.printf("%10s%13s\n",inString, accept1);
}
} // end main
} // end class
FSM类
// Finite State Machine Class
public class FSM
{
// Instance variables
public String alphabet;
public int stateTrans[][];
public int acceptState[];
private int cstate;
// Constructor function
public FSM(String A, int[][] ST, int[] AS)
{
int NSYMBOLS = A.length();
int NSTATES = AS.length;
// Alphabet
alphabet = "" + A;
// State transition table
stateTrans = new int[NSTATES][NSYMBOLS];
for(int r = 0; r < NSTATES; r++)
for(int c = 0; c < NSYMBOLS; c++)
stateTrans[r][c] = ST[r][c];
// Accept states
acceptState = new int[NSTATES];
for(int r = 0; r < NSTATES; r++)
acceptState[r] = AS[r];
// Start state
cstate = 0;
}
// Methods
public int getState()
{
return cstate;
}
public void setState(int state)
{
cstate = state;
return;
}
public int nextState(char symbol)
{
int nstate = -1;
int col = alphabet.indexOf(symbol);
if(col >= 0)
nstate = stateTrans[cstate][col];
return nstate;
}
public boolean accept(int state)
{
if(state < 0)
return false;
return (acceptState[state] != 0);
}
public boolean validString(String word)
{
cstate = 0;
for(int k = 0; k < word.length(); k++){
cstate = nextState(word.charAt(k));
System.out.print(cstate);
System.out.println(" " + word.charAt(k));
if(cstate < 0)
return false;
}
return accept(cstate);
}
} // end class
谢谢!
答案 0 :(得分:0)
这是我输入的简单方法,可以执行您想要的任务。
(big-bang world
(on-draw show-world)
(on-tick event1 1)
(on-tick event2 1))
我在理解您如何实现您的方法时遇到了麻烦,我认为这可能会更简单。我确定您包含在FSM类中的实例变量还有其他用途,但是我真的不需要任何一个分析字符串。只需使用这样的东西,它就应该很容易集成到您的代码中,因为它只需要字符串即可。希望这会有所帮助!