java - Finite State Machine to Search for "ABBA" -
i'm trying write while switch case kinda code modeling finite state machine searches string of , bs see if string "abba" present. when input "abba", outputs word found! it's supposed to. however, if input "aabba" doesn't find word & output right message. 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 evaluate..."); while(status != 4){ for(int = current; < word.length(); i++){ string part = word.substring(current, + 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 there if(part.equals("ab")){ status = 2; } else if(part.equals("aa"){ status = 1; current = 1; } break; case 2: //ab there if(part.equals("abb")){ status = 3; } else if(part.equals("aba"){ status = 1; current = 1; } break; case 3: //abb there if(part.equals("abba")){ status = 4; system.out.println("word found!"); } else if(part.equals("abbb"){ status = 0; current = i; } break; } } } } }
what can see ineffective in approache not use power of state machine. first of should understand drives machine through states. in example each sequential letter of input string does. since have taken state should check state next symbol switch machine. let me suggest following implementation..
here state diagram:
here code implementing diagram:
public boolean abbamatcher(string abba) { int state = 0; int symbol = 0; while (symbol < abba.length()){ char c = abba.charat(symbol); switch (state){ case 0: if(c == 'a'){ state = 1; }else{ state = 0; }; break; case 1: if(c == 'b'){ state = 2; }else{ state = 1; }; break; case 2: if(c == 'b'){ state = 3; }else{ state = 1; }; break; case 3: if(c == 'a'){ return true; }else{ state = 0; }; break; } symbol++; } return false; } this written more loop, while/switch construnction requirement.

Comments
Post a Comment