import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class Aufgabe1_Kellerautomat { private static String[] words = {"ZZO", "ZZOZZOO", "ZZZOO", "ZZOO", "ZZOZZO", "ZOZ"}; public static void main(String[] args) { for (String word : words) { calculate(word); } } public static boolean calculate(String word) { List wordChars = new ArrayList<>(); for (char symbol : word.toCharArray()) { wordChars.add(symbol); } ArrayList stack = new ArrayList<>(); stack.add('$'); int state = 0; //case 0 - 5 = q0 - q5, case -1 = Abfallzustand while (wordChars.size() > 0 || state >= 3) { char symbol; Character stackSymbol = stack.remove(stack.size() - 1); switch (state) { case 0: if (wordChars.remove(0) == 'Z' && stackSymbol == '$') { stack.add('$'); stack.add('Z'); state = 1; } else { dontAccept(word); return false; } break; case 1: if (wordChars.remove(0) == 'Z' && stackSymbol == 'Z') { stack.add('Z'); stack.add('Z'); state = 2; } else { dontAccept(word); return false; } break; case 2: symbol = wordChars.remove(0); if (isOperator(symbol) && stackSymbol == 'Z') { state = 3; } else if (symbol == 'Z' && stackSymbol == 'Z') { stack.add('Z'); stack.add('Z'); state = 2; } else if (symbol == 'Z' && stackSymbol == '$') { stack.add('$'); stack.add('Z'); state = 2; } else { dontAccept(word); return false; } break; case 3: if (stackSymbol == 'Z') { stack.add('Z'); state = 4; } else { dontAccept(word); return false; } break; case 4: if (wordChars.size() > 0) { symbol = wordChars.remove(0); if (symbol == 'Z' && stackSymbol == 'Z') { stack.add('Z'); stack.add('Z'); state = 2; } else if (isOperator(symbol) && stackSymbol == 'Z') { state = 3; } else { dontAccept(word); return false; } } else { if (stackSymbol == 'Z') { state = 5; } else { dontAccept(word); return false; } } break; case 5: if (stackSymbol == '$') { stack.add('$'); state = 6; } else { dontAccept(word); return false; } break; case 6: accept(word); return true; } } dontAccept(word); return false; } private static void dontAccept(String word) { System.out.println("Word: " + word + "\nnot accepted"); } private static void accept(String word) { System.out.println("Word: " + word + "\naccepted "); } private static boolean isOperator(char symbol){ return symbol == '+' || symbol == '*'; } }