Reputation: 908
here is my method, its just a nested loop:
IEnumerator startNewRound()
{
string st = "آبپتثجچحخدذرضطظعغفقکگلمنوهی";
for (int i = 0; i < st.Length; i++)
{
for (int j = i + 1; i < st.Length; j++)
{
for (int z = j + 1; z < st.Length; z++)
{
if (z > st.Length) continue;
yield return new WaitForSeconds(0.1f);
Debug.Log("I = " + i + " J = " + j + " Z= " + z);
}
}
}
}
suddenly inside the loop program freezes for some seconds and, 'j' counter changes and every thing blows up! here is my Log:
I cant understand what is wrong!
Upvotes: 0
Views: 95
Reputation: 136074
In your second nested loop, you mistakenly use i
instead of j
as the loop control variable:
for (int j = i + 1; i < st.Length; j++)
Should be
for (int j = i + 1; j < st.Length; j++)
Why does this cause a problem? Lets look at the pertinent part of the utput:
I = 0 J = 24 Z= 25
I = 0 J = 24 Z= 26
I = 0 J = 25 Z= 26
I = 0 J = 2147483647 Z= -2147483648
I = 0 J = 2147483647 Z= -2147483647
I = 0 J = 2147483647 Z= -2147483646
At the point that your code hits I=0, J=25 & z=26 (which is one less than the length of st
) the following happens:
z
gets incremented to 27z < st.Length
and thus ends that loopj
gets incremented to 26
z
to j+1
(27)z < st.Length
- false. Exit the loop without ever entering it to output anythingi < st.Length
- true and enters the loop.j
is incremented Upvotes: 11