17 State Machines
17 State Machines
3
Example I: Even or odd
The following machine determines whether the number of As in a string is even
or odd
Circles represent states; arrows represent transitions
A
even odd
start
A
4
Error states
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
5
Simplifying drawings I
State machines can get pretty complicated
The formal, mathematical definition of a state machine requires it
to have a transition from every state for every possible input
To satisfy this requirement, we often need an error state, so we can have
transitions for illegal (unrecognized) inputs
When we draw a state machine, we don’t need to draw the error
state--we can just assume it’s there
The error state is still part of the machine
Any input without a transition on our drawing is assumed to go to the
error state
Another simplification: Use * to indicate “all other characters”
This is a convention when drawing the machine—it does not mean we
look for an asterisk in the input
6
Example II: Nested parenthesis
The following example tests whether parentheses are properly
nested (up to 3 deep)
( ( (
OK
start
) ) ) )
* * * ( *
Error
How can we extend this machine to handle
* arbitrarily deep nesting?
7
Nested parentheses II
8
Nested parentheses III
( do count++
( do count=1
start
OK
) and ) and
count==1 count>1 do
do count=0 count--
This machine is based on a state machine, but it
obviously is not just a state machine
9
The states of a Thread
A Thread is an object that represents a single flow of
execution through a program
A Thread’s lifetime can be described by a state machine
waiting
10
Example: Making numbers bold
In HTML, you indicate boldface by surrounding the
characters with <b> ... </b>
Suppose we want to make all the integers bold in an HTML
page—we can write a state machine to do this
end of input
digit output
start end
output <b>digit </b>
12
Outline of the bold program
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 }
}
}
13
The two states
15
The End
16