End a else if statement C#
You can use a switch
statement on strings, too:
switch (turtleDir) {
case "left":
angle = -1.6f;
turtleDir = "lookingLeft";
Program.form.direction = "";
break;
case "lookingLeft":
angle = 3.15f;
turtleDir = "lookingDown";
break;
// other cases
}
This way, the switch
block 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 a case default:
at the end. Remember each of these cases needs to be terminated by a break
statement (or return
/throw
but 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 let turtleDir
cycle until every case has been executed and turtleDir
ends 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 change turtleDir
only 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 every case
statement. That's why your code gets executed over and over again. Also, if no direction is entered, clear it, too.
Comments
-
Sigh-AniDe over 1 year
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 theturtleDir
which is a string value indicating the directionturtleDir
has.The problem comes here at else if statements, when the
turtleDir
islookingleft
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"; } }