【发布时间】:2018-01-04 19:30:12
【问题描述】:
我正在尝试编写一个 while switch case 代码,用于对有限状态机进行建模,该状态机搜索一串 As 和 Bs 以查看字符串“ABBA”是否存在。当我只输入“ABBA”时,它会像预期的那样输出Word found!。但是,如果我输入 "AABBA" 它找不到单词并输出正确的消息。任何帮助表示赞赏。谢谢!
import java.util.*;
public class AB{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
String word = input.next();
int current = 0;
int status = 0;
System.out.println("Starting to evaluate...");
while(status != 4){
for(int i = current; i < word.length(); i++){
String part = word.substring(current, i + 1);
switch(status){
case 0: //start
if(part.equals("A")){
status = 1;
}
else if(part.equals("B"){
status = 0;
current = i;
}
break;
case 1: //A is there now
if(part.equals("AB")){
status = 2;
}
else if(part.equals("AA"){
status = 1;
current = 1;
}
break;
case 2: //AB is there now
if(part.equals("ABB")){
status = 3;
}
else if(part.equals("ABA"){
status = 1;
current = 1;
}
break;
case 3: //ABB is there now
if(part.equals("ABBA")){
status = 4;
System.out.println("Word found!");
}
else if(part.equals("ABBB"){
status = 0;
current = i;
}
break;
}
}
}
}
}
【问题讨论】:
-
while/switch 构造是必需的吗?
-
@AlexeyR。是的
-
我将 String word = input.next() 更改为 String word = "AABBA" 并且效果很好。你确定不是扫描仪问题。
-
附注 - 在状态机中,在每个步骤中只比较“下一个”字母更有意义。前面的字母已经在前面的步骤中测试过了,它们让你进入了当前的状态 (
status x),所以不需要再次比较整个字符串,只需额外的字符。 -
它实际上找到了
AABBA。请注意,如果您提供的第一个单词不包含ABBA,您的程序将永远卡在while循环中