Reputation: 29
Not sure if I've numbed my mind trying to figure this but I'm trying to get a loop to trigger again after it runs by changing its condition in a later branch of code based on user input. Here's the code:
int moveend = 1;
for (int move = 0; move < moveend; move++)
{
if (move < 1)
{
Console.WriteLine("Enter a direction to move\n");
//forloop that allows the output to cycle the legth of array and branch to a new line on 4th output
for (int i = 0; i < width; i++)
{
//for loop code
}
//This is the code i'm using to re trigger the previous loop with "move = 0"
ConsoleKeyInfo kb = Console.ReadKey();
if (kb.Key == ConsoleKey.UpArrow)
{
map[7, 1] = 1;
map[11, 1] = 0;
move = 0;
Console.WriteLine("FIre");
}
}
else
{
Console.WriteLine("END");
}
}
I'm not sure why it is that I can see the "Fire" with this code but it doesn't loop again despite the loop condition being reset within the loop. I expected it to reprint the loop info with the updated array coordinates map[7, 1] = 1; map[11, 1] = 0;
but it doesn't. Am I overlooking something or is there something I'm missing about loops?
Upvotes: 1
Views: 741
Reputation: 391306
The reason is that you set move
to 0, but it is already zero.
The loop can loosely be translated to this:
int move = 0;
while (move < moveend)
{
... rest of your code
move++;
}
So move
is 0 the whole time throughout the loop, and is increased at the end, and then it is no longer < moveend
.
To keep running the loop, perhaps you don't want a for
loop at all?
bool keepRunning = true;
while (keepRunning)
{
keepRunning = false;
... rest of your code
if (...)
keepRunning = true; // force another run through the loop
}
Upvotes: 1
Reputation: 14044
I am not sure why are you doing it like that I think this might help you to accomplish your task
bool dirtyBool = true;
while(dirtyBool)
{
if (move < 1)
{
Console.WriteLine("Enter a direction to move\n");
//forloop that allows the output to cycle the legth of array and branch to a new line on 4th output
for (int i = 0; i < width; i++)
{
//for loop code
}
//This is the code i'm using to re trigger the previous loop with "move = 0"
ConsoleKeyInfo kb = Console.ReadKey();
if (kb.Key == ConsoleKey.UpArrow)
{
map[7, 1] = 1;
map[11, 1] = 0;
move = 0;
dirtyBool=false;
Console.WriteLine("FIre");
}
}
else
{
dirtyBool=false;
Console.WriteLine("END");
}
}
I have added a variable dirtyBool of type Bool which will make loop it again. Modify the code according to your usablility
Upvotes: 0