首页 > 解决方案 > 有中断时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;
                                }
                            }
                        }

标签: c#.netvisual-studio

解决方案


您的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;
                
 }

推荐阅读