如何返回主菜单与许多菜单里面

本文关键字:菜单 许多 何返回 返回 | 更新日期: 2023-09-27 18:12:29

如果我的程序上有很多菜单,我如何在不使用任何循环的情况下返回主菜单?假设我需要"Y"作为返回,"N"作为结束程序。

static void Main(string[] args)
    {int choice;
        Console.WriteLine("Main Menu");
        Console.WriteLine("1. Rent");
        Console.WriteLine("2. Return");
        Console.WriteLine("3. Exit");
        choice = Convert.ToInt32(Console.ReadLine());
        while (choice!= 3)
        {
         if  (choice ==1)
          {...
           //when complete all thing in choice 1
           Console.WriteLine("Do you want to start over?(Y=Yes,N=No)");
           // in this part i need to go back to main menu with "Y" input and close program with "N"input
          }
         if (choice ==2)
          {...
           //when complete all thing in choice 2
          Console.WriteLine("Do you want to start over?(Y=Yes,N=No)");
           // doing like choice 1 }

如何返回主菜单与许多菜单里面

我会写不同的,但根据您的代码,这将得到您想要的。

  static void Main(string[] args)   
  {
      int choice = 0;
      while (choice != 3)
      {
           Console.WriteLine("Main Menu");
           Console.WriteLine("Rent=1");
           Console.WriteLine("Return=2");
           Console.WriteLine("Exit=3)");
           choice = GetUserChoice("What is your choice?", choice);
           if (choice == 1)
           {
              //when complete all thing in choice 1
              choice = GetUserChoice("Do you want to start over?(Y=1,N=3)", choice);
           }
           else if(choice == 2)
           {
               //when complete all thing in choice 2
               choice = GetUserChoice("Do you want to start over?(Y=1,N=3)", choice);
           }
       }
   }
   private static int GetUserChoice(string question, int choice)
   {
       Console.WriteLine(question);
       return  Convert.ToInt32(Console.ReadLine());
   }

请注意,在询问是否重新开始的选项中,我会让用户输入1代表Y(是),3代表N(否)。