我正在尝试实现这个自动机示例:http ://www.javacodegeeks.com/2012/03/automaton-implementation-in-java.html 。
但是,在运行程序时一直显示错误:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 3
at java.lang.String.charAt(String.java:686)
at mealy.Input.read(Input.java:7)
at mealy.States$4.next(Input.java:46)
at mealy.Test.main(Test.java:9)
我尝试修改导致错误的行,但没有任何改变。有人可以看看这个程序并帮助我找到解决方案吗?
我有以下 .java :
状态.java:
interface State {
public State next(Input in);
}
注意:我不得不将原来的“public Stat next()”更改为“public State next(Input in);”
输入.java:
class Input {
private String input;
private int current;
public Input(String input) {this.input = input;}
char read() { return input.charAt(current++); }
}
enum States implements State {
Init {
@Override
public State next(Input word) {
switch(word.read()) {
case 'a': return A;
default: return Fail;
}
}
},
A {
@Override
public State next(Input word) {
switch(word.read()) {
case 'a': return A;
case 'b': return B;
case 'c': return C;
case 'd': return null;
default: return Fail;
}
}
},
B {
@Override
public State next(Input word) {
switch(word.read()) {
case 'b': return B;
case 'c': return C;
case 'd': return null;
default: return Fail;
}
}
},
C {
@Override
public State next(Input word) {
switch(word.read()) {
case 'c': return C;
case 'd': return null;
default: return Fail;
}
}
},
Fail {
@Override
public State next(Input word) {
return Fail;
}
};
public abstract State next(Input word);
}
测试.java:
public class Test {
public static void main(String args[]){
State s;
Input in = new Input("abc");
for(s = States.Init; s != null || s != States.Fail; s = s.next(in)) {}
if(s == States.Init) {System.out.println("Valid!");}
else {System.out.println("Failed");}
}
}