Finite State Machine to Search for "ABBA"

Viewed 1212

I'm trying to write a while switch case kinda code for modeling a finite state machine that searches a string of As and Bs to see if the string "ABBA" is present. When I input just "ABBA", it outputs Word found! like it's supposed to. However, if I input "AABBA" it doesn't find the word & output the right message. Any help is appreciated. Thanks!

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;
                }
            }
        }
    }
}
2 Answers
Related