C# 如何避免在移动到同一循环中的另一个if语句时使用相同的迭代器?
我正在尝试使用C# 如何避免在移动到同一循环中的另一个if语句时使用相同的迭代器?,c#,C#,我正在尝试使用继续但看起来像-不正确; 每3次我都有相同的“I”值。在切换boolsfirsThreeDays和second-threedays之后第一次运行if(currentShiftCD!=3¤tShiftAB==3)和if(currentShiftDC!=3¤tShiftBA==3)时,如何跳过迭代器 我希望输出为:1,2,3,4,5,6..19,但具有相同的值: for(int i=1;i我不会使用continue来“解决”您的问题,只要在第一个ifif中使用
继续代码>但看起来像-不正确;
每3次我都有相同的“I”值。在切换boolsfirsThreeDays
和second-threedays之后第一次运行if(currentShiftCD!=3¤tShiftAB==3)
和if(currentShiftDC!=3¤tShiftBA==3)
时,如何跳过迭代器
我希望输出为:1,2,3,4,5,6..19,但具有相同的值:
for(int i=1;i我不会使用continue
来“解决”您的问题,只要在第一个if
if中使用else
子句即可
for (int i = 1; i <20; i++)
{
if (firstThreeDays)
{
if (currentShiftAB != 3)
{
currentShiftAB++;
Console.WriteLine(i + " A-B");
}
if (currentShiftCD != 3 & currentShiftAB == 3)
{
currentShiftCD++;
Console.WriteLine(i + " C-D");
}
if (currentShiftAB == 3 & currentShiftCD == 3)
{
firstThreeDays = false;
secondThreeDays = true;
currentShiftAB = 0;
currentShiftCD = 0;
}
}
else if (secondThreeDays)
{
if (currentShiftBA != 3)
{
currentShiftBA++;
Console.WriteLine(i + " B-A");
}
if (currentShiftDC != 3 & currentShiftBA == 3)
{
currentShiftDC++;
Console.WriteLine(i + " D-C");
}
if (currentShiftBA == 3 & currentShiftDC == 3)
{
secondThreeDays = false;
firstThreeDays = true;
currentShiftBA = 0;
currentShiftDC = 0;
}
}
}
Console.ReadLine();
for(int i=1;i问题在于前两个if语句的顺序,在前三天和第二个三天内。使用if、else if、else if
construct
// Suppose your loop has executed once. Now, currentShiftAB is 2.
if (currentShiftAB != 3) // currentShiftAB is not 3.It enters this if.
{
currentShiftAB++; // currentshiftAB is now 3.
Console.WriteLine(i + " A-B"); //It prints 3 A-B
}
// Now, currentShiftAB is 3 but currentShiftCD is not 3.
// your code enters this if condition as well at the same time.
// That's why you are getting duplicate output for i=3.
if (currentShiftCD != 3 & currentShiftAB == 3)
{
currentShiftCD++;
Console.WriteLine(i + " C-D");
}
哪个continue
不正确?发生了什么?你想要什么?你试图解决的根本问题是什么?所有A-B
,C-D
代表什么?你确定要使用&
而不是&
只需运行调试器并一步一步地检查代码。我想你需要使用其他工具吗f而不是一个if接一个if,否则循环可以进入每个if,你是对的…如果我把它放在第一个if的末尾-if(currentShiftAB==3){continue;},我有正确的输出。
// Suppose your loop has executed once. Now, currentShiftAB is 2.
if (currentShiftAB != 3) // currentShiftAB is not 3.It enters this if.
{
currentShiftAB++; // currentshiftAB is now 3.
Console.WriteLine(i + " A-B"); //It prints 3 A-B
}
// Now, currentShiftAB is 3 but currentShiftCD is not 3.
// your code enters this if condition as well at the same time.
// That's why you are getting duplicate output for i=3.
if (currentShiftCD != 3 & currentShiftAB == 3)
{
currentShiftCD++;
Console.WriteLine(i + " C-D");
}