pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

如何在 C# 中實(shí)現(xiàn)具有子菜單的控制臺(tái)菜單

How to implement a console menu having submenus in C#(如何在 C# 中實(shí)現(xiàn)具有子菜單的控制臺(tái)菜單)
本文介紹了如何在 C# 中實(shí)現(xiàn)具有子菜單的控制臺(tái)菜單的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!

問題描述

(C#) 我正在開發(fā)一個(gè)類似于 RedBox 的程序,它將具有客戶和經(jīng)理功能.我只是想在開始實(shí)現(xiàn)更多功能之前讓所有菜單正常工作,但我遇到了一個(gè)我似乎無法理解的錯(cuò)誤.我的問題似乎出在 CustomerMenu() 方法和 MainMenu() 方法中.我已經(jīng)添加了我擁有的所有內(nèi)容,以便您可以獲得完整的圖片.感謝任何幫助,因?yàn)槲胰匀挥悬c(diǎn)新,所以感謝任何提示,謝謝.

(C#) I am working on a program that is similar to RedBox which will have customer and manager functions. I am just trying to get all the menu's working correctly before I begin implementing more functions, but I am encountering an error that I can not seem to understand. My issue seems to be in the CustomerMenu() method and in the MainMenu() method. I have added all that I have so you can get the full picture. Any help is appreciated as I am still somewhat new so any tips are appreciated, thank you.

        MainMenu();
        Console.ReadKey();

    }
    static void MainMenu()
    {
        int userChoice = MainMenuChoice(); // Reading in the userChoice with the MenuChoice method

        if (userChoice == 3) // if user enters 3, the program ends
        {
            Console.WriteLine("Thank you, Goodbye!");
        }

        while (userChoice != 3)
        {
            if (userChoice == 1)
            {
                Console.WriteLine("Welcome to the customer menu!
"); // The customer menu is brought up if user enters 1
                CustomerMenu();
            }
            if (userChoice == 2)
            {
                Console.WriteLine("Welcome to the manager menu!
"); // The manager menu is brought up if user enters 2
                //ManagerMenu();
            }
            userChoice = MainMenuChoice(); // program ends
            if (userChoice == 3)
            {
                Console.WriteLine("Thank you for visiting VideoMart at University Boulevard, Goodbye!");

            }
        }

    }
    static int MainMenuChoice()
    {
        Console.WriteLine("-----------------------------------------------------------------------------------------------------------"); // introducing the user with the menu 
        Console.WriteLine("Welcome to VideoMart at University Boulevard!  
At VideoMart you are able to rent a variety of movies from many genres such as action, family, horror, etc!");
        Console.WriteLine("
Press 1 if you are a customer");
        Console.WriteLine("
Press 2 if you are a manager");
        Console.WriteLine("
Press 3 to Exit");
        Console.WriteLine("-----------------------------------------------------------------------------------------------------------");

        string choice = Console.ReadLine();
        Console.WriteLine();

        while (!(choice == "1" || choice == "2" || choice == "3")) // error checking
        {
            Console.WriteLine("Please try again");
            Console.WriteLine("Press 1 if you are a customer");
            Console.WriteLine("Press 2 if you are a manager");
            Console.WriteLine("Press 3 to Exit");

            choice = Console.ReadLine();
        }

        return int.Parse(choice);
    }

    }


    static void CustomerMenu() {

        int customerChoice = CustomerMenuChoice(); // Reading in the customerChoice into the CustomerMenuChoice method

        if (customerChoice == 5) // if user enters 5, the program ends
        {
            Console.WriteLine("Thank you for using VideoMart!");
        }

        while (customerChoice != 5)
        {
            if (customerChoice == 1)
            {
                Console.WriteLine("Press 1 to view movies available to rent.
"); // this option gives the user the opportunity to view all movies available to rent
                 //MoviesAvailable();
            }
            if (customerChoice == 2)
            {
                Console.WriteLine("Press 2 to rent a movie.
"); // this option gives the user the opportunity to rent a movie, with email address
                //RentMovie();
            }
            if (customerChoice == 3)
            {
                Console.WriteLine("Press 3 to view a list of movies you currently have rented.
"); // this option gives the user the opportunity to view movies a user currently has rented, with email address
                //RentMovie();
            }
            if (customerChoice == 4)
            {
                Console.WriteLine("Press 4 to return a movie rented.
"); // this option gives the user the opportunity to return a movie rented
                //RentMovie();
            }
            customerChoice = CustomerMenuChoice();
            if (customerChoice == 5)
            {
                Console.WriteLine("Thank you for visiting VideoMart at University Boulevard, Goodbye!");

            }
        }            
}
    static int CustomerMenuChoice()
    {
        Console.WriteLine("-----------------------------------------------------------------------------------------------------------"); // introducing the user with the menu 
        Console.WriteLine("Welcome to VideoMart at University Boulevard!  
Below is a list of actions that can be performed by customers!");
        Console.WriteLine("
Press 1 to view movies available to rent.");
        Console.WriteLine("
Press 2 to rent a movie.");
        Console.WriteLine("
Press 3 to view a list of movies you currently have rented.");
        Console.WriteLine("
Press 4 to return a movie rented.");
        Console.WriteLine("
Press 5 to exit.");
        Console.WriteLine("-----------------------------------------------------------------------------------------------------------");

        string customerChoice2 = Console.ReadLine();
        Console.WriteLine();

        while (!(customerChoice2 == "1" || customerChoice2 == "2" || customerChoice2 == "3" || customerChoice2 == "4") || customerChoice2 == "5") // error checking
        {
        Console.WriteLine("
Press 1 to view movies available to rent.");
        Console.WriteLine("
Press 2 to rent a movie.");
        Console.WriteLine("
Press 3 to view a list of movies you currently have rented.");
        Console.WriteLine("
Press 4 to return a movie rented.");
        Console.WriteLine("
Press 5 to exit.");

            customerChoice2 = Console.ReadLine();
        }

        return int.Parse(customerChoice2);
    }
}

推薦答案

使用平面菜單系統(tǒng)

您可以嘗試更正并稍微重構(gòu)一下.

You can try this corrected and a little refactored.

我們創(chuàng)建了一個(gè)獲取用戶選擇的方法,因此不再需要重復(fù)代碼.我們使用 uint 是因?yàn)檫x擇是肯定的,并且使用 TryParse 來轉(zhuǎn)換輸入的字符串.出錯(cuò)時(shí)返回 0,所以這里沒問題.

We created a method to get the user choice, so repeat code is no more needed. We use uint because choice is positive and TryParse to convert the inputed string. It returns 0 in case of error, so that's fine here.

我們還使用 lamda 來打印選擇字符串以不重復(fù)它們.

Also we use a lamda to print the choices strings to not repeat them.

接下來我們使用 switch 來管理選擇,以便代碼更干凈和可維護(hù).

Next we use a switch to manage choice so the code is more clean and maintainable.

清除菜單之間的控制臺(tái),我們提供根菜單和子菜單之間的導(dǎo)航.

The console is cleared between menus and we offer navigation between root and sub menus.

未來的改進(jìn)是使用運(yùn)行這些表的自動(dòng)菜單管理器創(chuàng)建菜單標(biāo)題、選項(xiàng)和相關(guān)方法的表格.只是稍微復(fù)雜一點(diǎn),但不要太多.這可以通過創(chuàng)建一些集合和一個(gè) MenuManager 類來完成.有了這樣的東西,你將擁有一個(gè)健壯的系統(tǒng),代碼很少,沒有重復(fù).

A future improvement is to create tables of menus headers, choices and associated methods... with a auto-menu manager that runs these tables. Just a little more complex but not too much. It can be done by creating some collections and a MenuManager class. With such thing, you will have a robust system with very few code and nothing repeated.

static void Test()
{
  MainMenu();
}

static uint GetUserChoice(Action printMenu, int choiceMax)
{
  uint choice = 0;
  Action getInput = () =>
  {
    uint.TryParse(Console.ReadLine(), out choice);
  };
  getInput();
  while ( choice < 1 || choice > choiceMax )
  {
    Console.WriteLine();
    Console.WriteLine("Please try again");
    printMenu();
    getInput();
  }
  return choice;
}

static void MainMenu()
{
  Action printMenu = () =>
  {
    Console.WriteLine("Press 1 if you are a customer");
    Console.WriteLine("Press 2 if you are a manager");
    Console.WriteLine("Press 3 to Exit");
  };
  Console.Clear();
  Console.WriteLine("-----------------------------------------------------------------------------------------------------------"); // introducing the user with the menu 
  Console.WriteLine("Welcome to VideoMart at University Boulevard!");
  Console.WriteLine("At VideoMart you are able to rent a variety of movies from many genres such as action, family, horror, etc!");
  Console.WriteLine();
  printMenu();
  Console.WriteLine("-----------------------------------------------------------------------------------------------------------");
  uint choice = GetUserChoice(printMenu, 3);
  switch ( choice )
  {
    case 1:
      CustomerMenu();
      break;
    case 2:
      //ManagerMenu();
      break;
    case 3:
      Console.WriteLine("Thank you for visiting VideoMart at University Boulevard, Goodbye!");
      break;
    default:
      throw new NotImplementedException();
  }
}

static void CustomerMenu()
{
  Action printMenu = () =>
  {
    Console.WriteLine("Press 1 to view movies available to rent.");
    Console.WriteLine("Press 2 to rent a movie.");
    Console.WriteLine("Press 3 to view a list of movies you currently have rented.");
    Console.WriteLine("Press 4 to return a movie rented.");
    Console.WriteLine("Press 5 to return to main menu.");
  };
  Console.Clear();
  Console.WriteLine("-----------------------------------------------------------------------------------------------------------"); // introducing the user with the menu 
  Console.WriteLine("Below is a list of actions that can be performed by customers!");
  Console.WriteLine();
  printMenu();
  Console.WriteLine("-----------------------------------------------------------------------------------------------------------");
  Console.WriteLine();
  uint choice = GetUserChoice(printMenu, 5);
  switch ( choice )
  {
    case 1:
      //MoviesAvailable();
      break;
    case 2:
      //RentMovie();
      break;
    case 3:
      //RentedMovies();
      break;
    case 4:
      //ReturnMovie();
      break;
    case 5:
      MainMenu();
      break;
    default:
      throw new NotImplementedException();
  }
}

使用自動(dòng)菜單管理器

這是菜單選項(xiàng)類:

public class MenuChoice
{
  public string Title { get; private set; }
  public Action Action { get; private set; }
  public MenuChoice(string title, Action action)
  {
    Title = title;
    Action = action;
  }
}

這是菜單類:

public class Menu
{

  private readonly string Separator = new string('-', 100);
  private string Header;
  private List<MenuChoice> Choices;
  private Menu Root;

  public Menu(string header, List<MenuChoice> choices, Menu root)
  {
    Header = header;
    Choices = choices;
    Root = root;
  }

  private void Print()
  {
    for ( int index = 0; index < Choices.Count; index++ )
      Console.WriteLine($"Press {index + 1} {Choices[index].Title}");
      Console.WriteLine($"Press {Choices.Count + 1} to " + 
                        $"{( Root == null ? "exit" : "go to previous menu" )}");
  }

  public void Run()
  {
    Console.Clear();
    Console.WriteLine(Separator);
    Console.WriteLine(Header);
    Console.WriteLine();
    Print();
    Console.WriteLine(Separator);
    uint choice = GetUserChoice();
    if ( choice == Choices.Count + 1 )
      if ( Root == null )
      {
        Console.WriteLine("Thank you for visiting VideoMart at University Boulevard, Goodbye!");
        return;
      }
      else
        Root.Run();
    else
    {
      var action = Choices[(int)choice - 1].Action;
      if ( action != null )
        action();
      else
      {
        Console.WriteLine("Not implemented yet, press a key to continue.");
        Console.ReadKey();
        Run();
      }
    }
  }

  uint GetUserChoice()
  {
    uint choice = 0;
    Action getInput = () =>
    {
      uint.TryParse(Console.ReadLine(), out choice);
    };
    getInput();
    while ( choice < 1 || choice > Choices.Count + 1 )
    {
      Console.WriteLine();
      Console.WriteLine("Please try again");
      Print();
      getInput();
    }
    return choice;
  }

}

這是菜單管理器類:

public class MenuManager
{
  private Menu Root;

  public MenuManager(Menu root)
  {
    Root = root;
  }

  public void Run()
  {
    Root.Run();
  }
}

這里是菜單管理器的初始化,在選擇中使用方法或另一個(gè)菜單而不是空值:

Here the menu manager initialization, using methods or another menu instead of null in choices:

var choicesMain = new List<MenuChoice>();
var choicesCustomer = new List<MenuChoice>();
var choicesManager = new List<MenuChoice>();

string headerMain = "Welcome to VideoMart at University Boulevard!" + Environment.NewLine +
                    "At VideoMart you are able to rent a variety of movies from many genres such as action, family, horror, etc!";
string headerCustomer = "Below is a list of actions that can be performed by customers!";
string headerManager = "Below is a list of actions that can be performed by managers!";

var root = new Menu(headerMain, choicesMain, null);
var menuCustomer = new Menu(headerCustomer, choicesCustomer, root);
var menuManager = new Menu(headerManager, choicesManager, root);

choicesMain.Add(new MenuChoice("if you are a customer", menuCustomer.Run));
choicesMain.Add(new MenuChoice("if you are a manager", menuManager.Run));

choicesCustomer.Add(new MenuChoice("to view movies available to rent.", null));
choicesCustomer.Add(new MenuChoice("to rent a movie.", null));
choicesCustomer.Add(new MenuChoice("to view a list of movies you currently have rented.", null));
choicesCustomer.Add(new MenuChoice("to return a movie rented.", null));

現(xiàn)在要做的是:

new MenuManager(root).Run();

這篇關(guān)于如何在 C# 中實(shí)現(xiàn)具有子菜單的控制臺(tái)菜單的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!

【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!

相關(guān)文檔推薦

Right-click on a Listbox in a Silverlight 4 app(右鍵單擊 Silverlight 4 應(yīng)用程序中的列表框)
WPF c# webbrowser scrolls over top menu(WPF c# webbrowser 在頂部菜單上滾動(dòng))
C# Console app - How do I make an interactive menu?(C# 控制臺(tái)應(yīng)用程序 - 如何制作交互式菜單?)
How to add an icon to System.Windows.Forms.MenuItem?(如何向 System.Windows.Forms.MenuItem 添加圖標(biāo)?)
How to avoid duplicate form creation in .NET Windows Forms?(如何避免在 .NET Windows Forms 中創(chuàng)建重復(fù)的表單?)
Building a database driven menu with ASP.NET, JQuery and Suckerfish(使用 ASP.NET、JQuery 和 Suckerfish 構(gòu)建數(shù)據(jù)庫(kù)驅(qū)動(dòng)的菜單)
主站蜘蛛池模板: 网站优化公司_SEO优化_北京关键词百度快速排名-智恒博网络 | 电杆荷载挠度测试仪-电杆荷载位移-管桩测试仪-北京绿野创能机电设备有限公司 | 有福网(yofus.com)洗照片冲印,毕业聚会纪念册相册制作个性DIY平台 | 暴风影音 | 丹佛斯压力传感器,WISE温度传感器,WISE压力开关,丹佛斯温度开关-上海力笙工业设备有限公司 | Trimos测长机_测高仪_TESA_mahr,WYLER水平仪,PWB对刀仪-德瑞华测量技术(苏州)有限公司 | 法钢特种钢材(上海)有限公司 - 耐磨钢板、高强度钢板销售加工 阀门智能定位器_电液动执行器_气动执行机构-赫尔法流体技术(北京)有限公司 | 凝胶成像系统(wb成像系统)百科-上海嘉鹏| 合肥展厅设计-安徽展台设计-合肥展览公司-安徽奥美展览工程有限公司 | 挨踢网-大家的导航! | UV-1800紫外光度计-紫外可见光度计厂家-翱艺仪器(上海)有限公司 | 电磁铁_推拉电磁铁_机械手电磁吸盘电磁铁厂家-广州思德隆电子公司 | 网络推广公司_网络营销方案策划_企业网络推广外包平台-上海澜推网络 | 商秀—企业短视频代运营_抖音企业号托管 | 产业规划_产业园区规划-产业投资选址及规划招商托管一体化服务商-中机院产业园区规划网 | 北京征地律师,征地拆迁律师,专业拆迁律师,北京拆迁律师,征地纠纷律师,征地诉讼律师,征地拆迁补偿,拆迁律师 - 北京凯诺律师事务所 | 蓄电池回收,ups电池后备电源回收,铅酸蓄电池回收,机房电源回收-广州益夫铅酸电池回收公司 | 宝元数控系统|对刀仪厂家|东莞机器人控制系统|东莞安川伺服-【鑫天驰智能科技】 | 洗地机_全自动洗地机_手推式洗地机【上海滢皓环保】 | uv固化机-丝印uv机-工业烤箱-五金蚀刻机-分拣输送机 - 保定市丰辉机械设备制造有限公司 | SF6环境监测系统-接地环流在线监测装置-瑟恩实业 | 安德建奇火花机-阿奇夏米尔慢走丝|高维|发那科-北京杰森柏汇 | 权威废金属|废塑料|废纸|废铜|废钢价格|再生资源回收行情报价中心-中废网 | 儿童语言障碍训练-武汉优佳加感统文化发展有限公司 | 新中天检测有限公司青岛分公司-山东|菏泽|济南|潍坊|泰安防雷检测验收 | 流水线电子称-钰恒-上下限报警电子秤-上海宿衡实业有限公司 | 翅片管散热器价格_钢制暖气片报价_钢制板式散热器厂家「河北冀春暖气片有限公司」 | 定时排水阀/排气阀-仪表三通旋塞阀-直角式脉冲电磁阀-永嘉良科阀门有限公司 | 北京四合院出租,北京四合院出售,北京平房买卖 - 顺益兴四合院 | 破碎机_上海破碎机_破碎机设备_破碎机厂家-上海山卓重工机械有限公司 | 污水提升器,污水提升泵,地下室排水,增压泵,雨水泵,智能供排水控制器-上海智流泵业有限公司 | 阿尔法-MDR2000无转子硫化仪-STM566 SATRA拉力试验机-青岛阿尔法仪器有限公司 | 齿轮减速机_齿轮减速电机-VEMT蜗轮蜗杆减速机马达生产厂家瓦玛特传动瑞环机电 | 天空彩票天下彩,天空彩天空彩票免费资料,天空彩票与你同行开奖,天下彩正版资料大全 | 拼装地板,悬浮地板厂家,悬浮式拼装运动地板-石家庄博超地板科技有限公司 | 铝合金线槽_铝型材加工_空调挡水板厂家-江阴炜福金属制品有限公司 | 洗地机_全自动洗地机_手推式洗地机【上海滢皓环保】 | 好杂志网-首页| 冷柜风机-冰柜电机-罩极电机-外转子风机-EC直流电机厂家-杭州金久电器有限公司 | 济南轻型钢结构/济南铁艺护栏/济南铁艺大门-济南燕翔铁艺制品有限公司 | 代办建筑资质升级-建筑资质延期就找上海国信启航 |