Your
younger brother is still trying to learn to program, but he keeps
having problems. He claims that the programs
don’t work properly when he types them in. He is trying to get the
Color Nerve game to work, but every time he runs the program,
the yellow intensity gets brighter whether he presses the button or
not. You take a look at his program and find the following code in the Update method:
if (pad1.Buttons.Y == ButtonState.Pressed ||
pad1.DPad.Down == ButtonState.Pressed ||
keys.IsKeyDown(Keys.Y)) ;
{
redIntensity++;
greenIntensity++;
}
This is the only part of
the program where the yellow intensity is being increased, and it seems
that the condition is being ignored.
This looks perfectly okay,
and it seems to compile and run correctly, but it seems to be making
the yellow intensity brighter every time. At this point, it is a good
idea to look at Microsoft Visual Studio and see if the compiler is
trying to tell you anything about the code. Figure 1 shows your brother’s code after he has compiled it.
Your
attention is drawn to the bottom left corner, where the message
"Possible mistaken empty statement" appears. If you double-click this
message, you find that the cursor moves to a point just after the if condition (I’ve drawn a circle around it in Figure 1).
The C# compiler is trying
to tell us something about this statement. If we go back to the
original listing, we find that your brother has added an extra semicolon
at the end of the condition. The problem is that this ends the
statement controlled by the condition. So if the R button or the R key
is pressed or the Dpad is pressed down, the program decides to do
nothing (an empty statement) and then goes on and performs the next
statements no matter what, leading to the effect that we are seeing. Figure 2 shows how this happens.
You remove the
semicolon, the warning goes away, and the program works fine. Your
younger brother is now starting to revise his opinion of you and offers
to take out the trash that night, even though it is your turn.
Note:
The Great Programmer has
been watching all this with approval. She figures that it is always a
good idea to try to help people who are stuck with a problem. Sometimes
when a programmer working on uncovering a bug has the chance to explain
what is going wrong with a piece of code to an innocent bystander, that
can be enough to allow the programmer to work out what is broken. That
means you can get a reputation as a fearsome bug fixer just by standing
by. Furthermore, seeing what mistakes other people make can give you
hints on things that you need to look out for when your programs go
wrong. Oh, and sometimes you get your trash taken out for free.