c# - 有中断时for循环继续循环
问题描述
我正在尝试制作一个停车场程序,其中一个功能是移动车辆。它正在工作,对象正在改变数组中的位置,只是循环继续并且它崩溃了,因为parkingLot[i, j].RegNummer 在第二次循环时为空。在我“移动”一辆车后,如何阻止它再次循环?我希望它打破并返回菜单。(这是在连接到菜单的开关盒中)
Console.WriteLine("Enter the licensenumber of the vehicle that you want to move: ");
string lNumber = Console.ReadLine();
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 2; j++)
{
if (lNumber == parkingLot[i, j].RegNummer)
{
Console.WriteLine("Enter the space you want to move it to: ");
int space = int.Parse(Console.ReadLine());
int space1 = space - 1;
if (parkingLot[space1, 0] == null)
{
parkingLot[space1, 0] = parkingLot[i, j];
parkingLot[i, j] = null;
Console.WriteLine("The vehicle with licensenumber {0} has been moved to space {1}", lNumber, space);
break;
}
}
else
{
Console.WriteLine("The vehicle with licensenumber {0} could not be found!", lNumber);
break;
}
}
}
解决方案
您的break
语句退出内部for
循环,如果您需要退出外部for
循环,我建议使用 a boolean
,并检查它是否true
要退出外部循环。当您满足内部for
循环的条件时,将其设置为true
:
string lNumber = Console.ReadLine();
bool exitOuter = false; //Use boolean to exit outer for loop
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 2; j++)
{
if (lNumber == parkingLot[i, j].RegNummer)
{
Console.WriteLine("Enter the space you want to move it to: ");
int space = int.Parse(Console.ReadLine());
int space1 = space - 1;
if (parkingLot[space1, 0] == null)
{
parkingLot[space1, 0] = parkingLot[i, j];
parkingLot[i, j] = null;
Console.WriteLine("The vehicle with licensenumber {0} has been moved to space {1}", lNumber, space);
exitOuter = true; //Set boolean to true to exit outer for loop
break;
}
}
else
{
Console.WriteLine("The vehicle with licensenumber {0} could not be found!", lNumber);
break;
}
}
//Check boolean to break outer for loop
if(exitOuter)
break;
}
推荐阅读
- python - Sqlalchemy 连接两个表
- windows - 如何设置 xperf 使其更频繁地写入日志文件?
- c++ - 作为模板类型参数,为什么 type[N] 不匹配它的专用版本----模板
S级 - git - 无法在git中推送二进制文件
- r - 根据分组变量返回数字
- javascript - 前端应用程序上的 dateTime 正在更改(angularjs 1.xx)
- python - 如何解决此“如果不是唯一参数,则生成器表达式必须加括号”错误?
- c# - 在 newtonsoft c# 中处理多态值
- excel - 运行时错误 -2147024809 (80070057) 指定的值超出了形状的范围
- amazon-s3 - 使用 SSE 将文件上传到 S3