I didn’t know what else to use in this case but an if statement.
What I am trying to do is I am getting a value string direction; from a Windows form and checking if it has the value I am looking for. Then checking if the turtleDir which is a string value indicating the direction turtleDir has.
The problem comes here at else if statements, when the turtleDir is lookingleft it does all of the else if statements. What I want it to do is after it has done that else if statement it needs to stop and wait for the next command. not go through all the statements.
Can someone please advise me on how to fix it and what I am doing wrong?
Here is the code:
else if ( Program.form.direction == "right" )
{
if ( turtleDir == "left" )
{
angle = -1.6f;
turtleDir = "lookingLeft";
Program.form.direction = "";
}
else if ( turtleDir == "lookingLeft" )
{
angle = 3.15f;
turtleDir = "lookingDown";
}
else if ( turtleDir == "lookingDown" )
{
angle = 1.6f;
turtleDir = "lookingRight";
}
else if ( turtleDir == "lookingRight" )
{
angle = 0.0f;
turtleDir = "lookingUp";
}
}
You can use a
switchstatement on strings, too:This way, the
switchblock is always exited after your instructions are done. You can also specify what to do when the string matches none of these values by adding acase default:at the end. Remember each of these cases needs to be terminated by abreakstatement (orreturn/throwbut i don’t think you need those in this case).If still every case is executed, your problem lies somewhere else. If a method contains this code and is called starting with e.g.
turtleDir == "left", each successive call of the method will letturtleDircycle until every case has been executed andturtleDirends up with the final value"lookingUp". So look at your control flow and maybe keep track whether you already performed this check. Maybe keep track of the elapsed time and changeturtleDironly if it has been in a particular state for a while (i don’t know your requirements).EDIT: You should set
Program.form.direction = ""in everycasestatement. That’s why your code gets executed over and over again. Also, if no direction is entered, clear it, too.