我試圖編寫一個while開關案例有點代碼建模一個有限狀態機的搜索字符串「ABBA」是否存在的有限狀態機。當我輸入「ABBA」時,它會輸出Word found!
。但是,如果我輸入"AABBA"
它不會找到單詞&輸出正確的消息。任何幫助表示讚賞。謝謝!有限狀態機搜索「ABBA」
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;
}
}
}
}
}
而/開關結構是一個要求? –
@AlexeyR。是的它是 – Anna
我改變了String word = input.next()爲String word =「AABBA」,它工作正常。你確定這不是一個掃描儀問題。 – Malphrush