We were given a problem that asks to use the letters QDN(Quarter, Dime, Nickel) to create a finite state machine that only accepts if they add to 40 cents. I have the basics down for using an IF statement concept. I was wondering if there is an easier way to do this that takes less time?
I've tried making tons of if cases but there are a lot of steps to using that method.
public class FSA2_rpf4961 {
public static void main(String[] args) {
//The program will read in a sequence of strings and test them against a
//FSM. Your strings may not contain blank spaces
System.out.println("Enter string to test or q to terminate");
Scanner in = new Scanner (System.in);
String testString = in.next();
while (!testString.equals("q"))
{
String testOutput = applyFSA2(testString);
System.out.println("For the test string "+testString+
", the FSM output is "+testOutput);
System.out.println("Enter next string to test or q to terminate:");
testString = in.next();
}
in.close();
}
public static String applyFSA(String s) {
String currentOut = "0"; // initial output in s0
String currentState = "s0"; // initial state
int i = 0;
while (i<s.length())
{
//quarter first
if (currentState.equals("s0") && s.charAt(i) == 'q')
{
currentState = "s1";
currentOut += 25; // collect output on move to s1
}
else if (currentState.equals("s1") && s.charAt(i) == 'd') {
currentState = "s2";
currentOut += 10;
}
else if (currentState.equals("s2") && s.charAt(i) == 'n') {
currentState = "s3";
currentOut += 5;
}
else if (currentState.equals("s1") && s.charAt(i) == 'n') {
currentState = "s4";
currentOut += 5;
}
else if (currentState.equals("s4") && s.charAt(i) == 'd') {
currentState = "s3";
currentOut += 10;
}
//dime first
else if (currentState.equals("s0") && s.charAt(i) == 'd')
{
currentState = "s5";
currentOut += 10; // d
}
We need it to only accept if it adds to 40 cents. This is very confusing for me to grasp.
Aucun commentaire:
Enregistrer un commentaire