首页 > 解决方案 > 如何允许用户随时从控制台退出 C# 输入

问题描述

我对 C# 编程很陌生,所以对我来说很赤裸裸。我目前正在尝试在基于菜单的控制台中为 BMI 计算器制作一段代码,该控制台允许用户从不同的选项中进行选择,并为他们提供不同的结果。

我还没有完成我的代码,但一切都相对顺利,直到我被告知 - “在程序运行时的任何阶段也应该有一个'退出'或终止的选项。”

我查看了多个论坛并试图找到答案,但我都无法使用我的代码。我希望这里有人能够帮助我并指出我正确的方向。

这是我目前正在使用的代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BMI_Application
{
    class Program
    {
        static void Main(string[] args)
        {
            bool showMenu = true;
            while (showMenu)
            {
                showMenu = MainMenu();
            }

        }

        private static void Calculator()
        {

        }
        private static bool MainMenu()
        {

            string bmi = "You have selected the BMI Calculator";
            float height;
            float weight;
            float sum1; // Heightx2
            float sum2; // Weight / sum1
            
            Console.WriteLine("Please select an option");
                Console.WriteLine("1: BMI Calculator");
                Console.WriteLine("2: Membership Rates");
                Console.WriteLine("3: Close Menu");
                Console.WriteLine("\r\nPlease enter 1, 2 or 3");
                Console.WriteLine("\r\nYou can also write 'bye' at any time to leave");

            switch (Console.ReadLine())
            {
                case "1":
                    Console.Clear();
                        Console.WriteLine(bmi);
                        Console.WriteLine("Please enter your Height in Metres");
                        height = float.Parse(Console.ReadLine());
                        Console.WriteLine("Please enter your Weight in Kilograms");
                        weight = float.Parse(Console.ReadLine());
                        sum1 = height * height;
                        sum2 = weight / sum1;
                        Console.WriteLine("Your BMI is : {0}", sum2); // Next part is - based on their BMI Level, writing if they are underweight etc
                    if (sum2 <= 18.5)
                    {
                        Console.WriteLine("Your BMI level indicates that your are 'Underweight' "); // Underweight
                    }
                    if (sum2 >= 18.5 && sum2 <= 25)
                    {
                        Console.WriteLine("Your BMI level indicates that you are 'Normal' weight"); // Normal
                    }
                    if (sum2 >= 25 && sum2 <= 30)
                    {
                        Console.WriteLine("Your BMI level indicates that you are 'Overweight' ");// Overweight
                    }
                    if (sum2 >= 30)
                    {
                        Console.WriteLine("Your BMI level indicates that you are 'Obese' "); // Obese
                    }
                        Console.WriteLine("\r\nPress any key to return back to main menu");
                        Console.ReadKey();
                        Console.Clear();
                        return true;

                    case "2":
                        Console.Clear();
                        Console.WriteLine("You have selected the Membership Rates");
                        Console.WriteLine("What Membership would you like?");
                        return true;
                    case "3":
                        Console.WriteLine("You have selected to close the menu, press any key to continue"); // Terminate
                        Console.ReadKey();
                        return false;
                    case "bye":
                        Console.WriteLine("Goodbye! Push any key to get out of here!");
                        Console.ReadKey();
                        return false;

                    default:
                        Console.Clear();
                        Console.WriteLine("That is not a valid number, please enter 1, 2 or 3"); // Not valid entry
                        Console.WriteLine(" ");
                        return true;
                }
            }
        }
            
    }

例如,关于如何通过输入“退出”一词让用户退出控制台的任何想法?

非常感谢

标签: c#inputexit

解决方案


因此,如果您想允许用户在任何阶段输入诸如“退出”之类的文本以退出程序,那么在您读取输入的每个点都需要支持这一点。

您的代码目前的结构方式很困难,因为您的代码中基本上有 1 个方法可以做所有事情。而且您实际上是将“计算器”与应该分开的“菜单”混合在一起。

如果您查看您的代码,那么您实际上会发现您多次重复代码部分,只是略有不同(向/从控制台写入和读取)。相反,您需要对代码进行结构化,以减少重复代码,而是将其拆分为单独的方法。

这实际上是您的程序的症结所在。因为您的代码的结构方式,如果不重新编写它,您将无法轻松地调整它以支持新需求。

现在我不会为你重写你的代码,但我会给你提示一种方法来部分地做到这一点(还有其他方法!)尝试将写入和读取分离到一个单独的方法中。然后,您还可以在单​​独的方法中检查“退出”一词。

所以伪代码会是这样的;

//do something in your method
var inputText = WriteAndGetInput("Please select option 1,2,3\r\nBlah blah blah \r\n");
CheckForExit(inputText);

//If you reach here, then Exit was not entered so carry on with your program and check for your real input.
//Try to use methods as to not repeat code.


//Method to write to console and get input
private static string WriteAndGetInput(string textToOutput)
{
       Console.WriteLine(textToOutput);
       return Console.ReadLine();  
}

//method to check if user typed exit
private static void CheckForExit(string inputText)
{
    if (inputText.Equals("exit"))
    {
        Console.WriteLine("You chose to exit.   Goodbye!");
        System.Environment.Exit(0); 
    }
}

推荐阅读