









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!










This is the kind of state machine you learn about in your math classes When you program a state machine, you don’t have that restriction
The following machine determines whether the number of As in a string is even or odd Circles represent states; arrows represent transitions
Inputs are the characters of a string The “output” is the resultant state The double circle represents a “final” (accepting) state
start even^ odd A
anything but A anything but A
Again, a state machine is a way of doing certain kinds of computations The input is a sequence of values (typically, a String) Some inputs may be illegal (for example, syntax errors in a program) A state machine is used to recognize certain kinds of inputs We say the machine succeeds if it recognizes its input, otherwise it fails Some states may be marked as final states (they are drawn with concentric circles) A state machine succeeds if: It is in a final state when it reaches the end of its input A state machine fails if: It encounters an input for which it has no defined transition It reaches the end of its input, but is not in a final state State machines may have a error state with the following characteristics: The error state is not a final state An unexpected input will cause a transition to the error state All subsequent inputs cause the state machine to remain in the error state
The following example tests whether parentheses are properly nested (up to 3 deep)
How can we extend this machine to handle arbitrarily deep nesting?
start )
Error
We need to count how deep we are into a parenthesis nest: 1, 2, 3, ..., 821, ... The only memory a state machine has is which state it is in
ready
waiting
start running dead
In HTML, you indicate boldface by surrounding the characters with ...
Suppose we want to make all the integers bold in an HTML page—we can write a state machine to do this
digit output digit
nondigit *: output * output nondigit
end of input output start
digit output digit
end
void run() { int state = NORMAL; for (int i = 0; i < testString.length(); i++) { char ch = testString.charAt(i); switch (state) { case NORMAL: { not inside a number } case NUMBER: { inside a number } } } if (state == NUMBER) result.append("");
case NORMAL: if (Character.isDigit(ch)) { result.append("" + ch); state = NUMBER; break; } else { result.append(ch); } break;
case NUMBER: if (!Character.isDigit(ch)) { result.append("" + ch); state = NORMAL; break; } else { result.append(ch); } break;