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)的菜單)
主站蜘蛛池模板: 上海三信|ph计|酸度计|电导率仪-艾科仪器 | 胜为光纤光缆_光纤跳线_单模尾纤_光纤收发器_ODF光纤配线架厂家直销_北京睿创胜为科技有限公司 - 北京睿创胜为科技有限公司 | 钢结构-钢结构厂房-钢结构工程[江苏海逵钢构厂] | 爆破器材运输车|烟花爆竹运输车|1-9类危险品厢式运输车|湖北江南专用特种汽车有限公司 | 步进电机_agv电机_伺服马达-伺服轮毂电机-和利时电机 | 聚氨酯催化剂K15,延迟催化剂SA-1,叔胺延迟催化剂,DBU,二甲基哌嗪,催化剂TMR-2,-聚氨酯催化剂生产厂家 | 臭氧实验装置_实验室臭氧发生器-北京同林臭氧装置网 | 手持式浮游菌采样器-全排二级生物安全柜-浙江孚夏医疗科技有限公司 | 硬齿面减速机_厂家-山东安吉富传动设备股份有限公司 | 电镀电源整流器_高频电解电源_单脉双脉冲电源 - 东阳市旭东电子科技 | 安规_综合测试仪,电器安全性能综合测试仪,低压母线槽安规综合测试仪-青岛合众电子有限公司 | 车牌识别道闸_停车场收费系统_人脸识别考勤机_速通门闸机_充电桩厂家_中全清茂官网 | 十字轴_十字轴万向节_十字轴总成-南京万传机械有限公司 | 列管冷凝器,刮板蒸发器,外盘管反应釜厂家-无锡曼旺化工设备有限公司 | 5nd音乐网|最新流行歌曲|MP3歌曲免费下载|好听的歌|音乐下载 免费听mp3音乐 | 低温等离子清洗机(双气路进口)-嘉润万丰 | 电表箱-浙江迈峰电力设备有限公司-电表箱专业制造商 | 交变/复合盐雾试验箱-高低温冲击试验箱_安奈设备产品供应杭州/江苏南京/安徽马鞍山合肥等全国各地 | ★店家乐|服装销售管理软件|服装店收银系统|内衣店鞋店进销存软件|连锁店管理软件|收银软件手机版|会员管理系统-手机版,云版,App | 深圳公司注册-工商注册代理-注册公司流程和费用_护航财税 | 大型多片锯,圆木多片锯,方木多片锯,板材多片锯-祥富机械有限公司 | 航拍_专业的无人机航拍摄影门户社区网站_航拍网 | 电动不锈钢套筒阀-球面偏置气动钟阀-三通换向阀止回阀-永嘉鸿宇阀门有限公司 | 即用型透析袋,透析袋夹子,药敏纸片,L型涂布棒-上海桥星贸易有限公司 | 石英砂矿石色选机_履带辣椒色选机_X光异物检测机-合肥幼狮光电科技 | 齿轮减速机电机一体机_齿轮减速箱加电机一体化-德国BOSERL蜗轮蜗杆减速机电机生产厂家 | 上海软件开发-上海软件公司-软件外包-企业软件定制开发公司-咏熠科技 | 卓能JOINTLEAN端子连接器厂家-专业提供PCB接线端子|轨道式端子|重载连接器|欧式连接器等电气连接产品和服务 | 合肥宠物店装修_合肥宠物美容院装修_合肥宠物医院设计装修公司-安徽盛世和居装饰 | 淋巴细胞分离液_口腔医疗器材-精欣华医疗器械(无锡)有限公司 | 自动气象站_农业气象站_超声波气象站_防爆气象站-山东万象环境科技有限公司 | 岩棉切条机厂家_玻璃棉裁条机_水泥基保温板设备-廊坊鹏恒机械 | 山东包装,山东印刷厂,济南印刷厂-济南富丽彩印刷有限公司 | 1000帧高速摄像机|工业高速相机厂家|科天健光电技术 | 湖北省煤炭供应链综合服务平台| 山东信蓝建设有限公司官网 | 深圳宣传片制作-企业宣传视频制作-产品视频拍摄-产品动画制作-短视频拍摄制作公司 | 防爆电机-高压防爆电机-ybx4电动机厂家-河南省南洋防爆电机有限公司 | 武汉刮刮奖_刮刮卡印刷厂_为企业提供门票印刷_武汉合格证印刷_现金劵代金券印刷制作 - 武汉泽雅印刷有限公司 | 真石漆,山东真石漆,真石漆厂家,真石漆价格-山东新佳涂料有限公司 | 洗砂机械-球磨制砂机-洗沙制砂机械设备_青州冠诚重工机械有限公司 |