我已经编写了一个Java程序来代表使用switch语句的DFA,但是它不会接受它应该做的单词。 我已经尝试添加一个单独的案例来发送最终状态以输出“接受的单词”#39;或者'字不被接受'但这没有用。 接受的示例词应该是: 谷歌 ggle xxgooooooglexeg
到目前为止我的代码:
public static void main(String[] args) {
System.out.println("Enter a word to run on the DFA:");
Scanner scanner = new Scanner(System.in);
String string = scanner.nextLine();
int state = 1;
for (char s : string.toCharArray()) {
switch (state) {
case (1): {
if (s == 'e' || s == 'l' || s == 'o' || s == 'x') {
state = 1;
} else if (s == 'g') {
state = 2;
}
}
break;
case (2): {
if (s == 'e' || s == 'l' || s == 'x') {
state = 1; {
} if (s == 'o') {
state = 2;
} else if (s == 'g') {
state = 3;
}
}
}
break;
case (3): {
if (s == 'e' || s == 'x') {
state = 1; {
} if (s == 'g' || s == 'o') {
state = 2;
} else if (s == 'l') {
state = 4;
}
}
break; }
case (4): {
if (s == 'g' || s == 'l' || s == 'o' || s == 'x') {
state = 1;
} else if (s == 'e') {
state = 5;
}
break; }
case (5): {
if (s == 'e' || s == 'g' || s == 'l' || s == 'o' || s == 'x') {
state = 5;
} else {
state = 5;
}
break; }
}
}
if (state == 5) {
System.out.println("Word accepted");
} else {
System.out.println("Word not accepted");
scanner.close();
}
}
P.S:我知道如果其他陈述很慢,但对于像这样的小型程序似乎很快。
答案 0 :(得分:0)
您的代码中存在很多问题。尝试正确缩进代码并查看打开和关闭括号的位置。
例如:
state = 1; {}
if-else if
包含在第一个if
语句中。鉴于您的输入和预期输出,我假设这是错误的。 以下是有效的格式化代码:
for (char s : string.toCharArray()) {
switch (state) {
case (1): {
if (s == 'e' || s == 'l' || s == 'o' || s == 'x') {
state = 1;
} else if (s == 'g') {
state = 2;
}
break;
}
case (2): {
if (s == 'e' || s == 'l' || s == 'x') {
state = 1;
} else if (s == 'o') {
state = 2;
} else if (s == 'g') {
state = 3;
}
break;
}
case (3): {
if (s == 'e' || s == 'x') {
state = 1;
} else if (s == 'g' || s == 'o') {
state = 2;
} else if (s == 'l') {
state = 4;
}
break;
}
case (4): {
if (s == 'g' || s == 'l' || s == 'o' || s == 'x') {
state = 1;
} else if (s == 'e') {
state = 5;
}
break;
}
case (5): {
if (s == 'e' || s == 'g' || s == 'l' || s == 'o' || s == 'x') {
state = 5;
} else {
state = 5;
}
break;
}
}
}