import java.nio.charset.StandardCharsets;
import java.util.*;
public class ScannerTool {
public static class DFA {
private record DFAState<E extends Comparable<E>>(
Map<E, DFAState<E>> onAcceptStates,
DFAState<E> onDeniedState,
String onAcceptOutput,
String onDeniedOutput) {
public Map.Entry<String, DFAState<E>> next(E input) {
if (onAcceptStates.containsKey(input)) {
return new AbstractMap.SimpleEntry<>(onAcceptOutput, onAcceptStates.get(input));
}
return new AbstractMap.SimpleEntry<>(onDeniedOutput, onDeniedState);
}
}
private DFAState<Character> currentState;
private final DFAState<Character> acceptedFinalState =
new DFAState<>(null, null, "Meeh.", "Meeh.");
private final DFAState<Character> rejectingFinalState =
new DFAState<>(null, null, "Meeeeh.", "Meeeeh.");
public DFA() {
DFAState<Character> state1 =
new DFAState<>(
Map.of('A', acceptedFinalState, 'B', acceptedFinalState),
rejectingFinalState,
"Du hast diesmal A oder B eingegeben.",
"Du hast zu oft nicht A oder B eingegeben.");
currentState =
new DFAState<>(
Map.of('A', acceptedFinalState, 'B', acceptedFinalState),
state1,
"Du hast A oder B eingegeben.",
"Versuchs nochmal.");
}
public Map.Entry<String, Boolean> next(Character input) {
Map.Entry<String, DFAState<Character>> next = currentState.next(input);
currentState = next.getValue();
return new AbstractMap.SimpleEntry<>(
next.getKey(), currentState == acceptedFinalState || currentState == rejectingFinalState);
}
}
public static void main(String[] args) {
DFA dfa = new DFA();
boolean validInput = true;
do {
System.out.println("Gib A oder B ein:");
Optional<Character> c = nextCharacter();
if (c.isPresent()) {
Map.Entry<String, Boolean> next = dfa.next(c.get());
System.out.println(next.getKey());
validInput = !next.getValue();
}
} while (validInput);
}
public static Optional<Character> nextCharacter() {
String l = new Scanner(System.in, StandardCharsets.UTF_8).nextLine();
if (l != null && !l.isEmpty()) {
return Optional.of(l.charAt(0));
}
return Optional.empty();
}
}