If和Switch语句;是否有更简单的方法来生成此代码?

时间:2016-09-12 19:31:03

标签: c# visual-studio if-statement switch-statement

我的代码如下:

namespace Calculation
{
    class Program
    {
    static void Main(string[] args)
    {
        Console.WriteLine("This is a system to calculate speed, distance or time.");
        Console.WriteLine("1 = Speed - 2 = Distance - 3 = time");
        Console.WriteLine("Please enter which calculation you would like to perform. 1, 2 or 3");

        string userCalculation = Console.ReadLine();
        int Calculation = int.Parse(userCalculation);

        if(Calculation < 1)
        {
            Console.WriteLine("Please enter a number greater than or equal to 1 but less than 3.");
        }

        if (Calculation > 3)
        {
            Console.WriteLine("Please enter a number less than 3 but greater than or equal to 1.");
        }

        else
        {
            switch (Calculation)
            {
                //This statement calculates speed.
                case 1:
                    Console.WriteLine("You have chose to calculate speed. S = D/T");

                    Console.WriteLine("To work this out you need to firstly enter your distance in metres");
                    string userDistance = Console.ReadLine();
                    int Distance = int.Parse(userDistance);

                    Console.WriteLine("Now enter your time in seconds.");
                    string userTime = Console.ReadLine();
                    int Time = int.Parse(userTime);

                    Console.WriteLine("Your speed is " + Distance / Time + " m/s");
                    Console.WriteLine("In MPH this is " + Distance / Time * 2.23 + "MPH");
                    break;

                //This statement calculates distance.
                case 2:
                    Console.WriteLine("You have chose to calculate distance. D = SxT");

                    Console.WriteLine("To work this out you need to firstly enter your speed");
                    string userSpeed = Console.ReadLine();
                    int Speed = int.Parse(userSpeed);

                    Console.WriteLine("Now enter your time in hours.");
                    string userTime1 = Console.ReadLine();
                    double Time1 = double.Parse(userTime1);

                    Console.WriteLine("Your Distance is " + Speed * Time1 + " miles");
                    break;

                //This statement calculates time.
                case 3:
                    Console.WriteLine("You have chose to calculate Time. T = D/S");

                    Console.WriteLine("To work this out you need to firstly enter your distance in miles.");
                    string userMiles = Console.ReadLine();
                    int Miles = int.Parse(userMiles);

                    Console.WriteLine("Now enter your Speed in MPH.");
                    string userSpeed2 = Console.ReadLine();
                    double Speed2 = double.Parse(userSpeed2);

                    Console.WriteLine("Your Time is " + Miles / Speed2 + "hours.");
                    Console.WriteLine("This would be " + Miles / Speed2 * 60 + " minutes");
                    break;
            }
        }

    }
}
}

5 个答案:

答案 0 :(得分:0)

首先,为了获得更好的可维护性指数,最好将这3种算法分成单独的函数并调用它们,或者至少进行计算。
关于if / switch,您可以在交换机末尾使用default: Console.WriteLine("Please enter a number greater than or equal to 1 but less than 3."); break; 个案例

src/styles/_config.sass

希望它有所帮助。

答案 1 :(得分:0)

首先,或许像这样(航空代码):

case 1:
    Console.WriteLine("You have chose to calculate speed. S = D/T");

    int Distance = GetNumericInput("To work this out you need to firstly enter your distance in metres");
    int Time = GetNumericInput("Now enter your time in seconds.");

    Console.WriteLine("Your speed is " + Distance / Time + " m/s");
    Console.WriteLine("In MPH this is " + Distance / Time * 2.23 + "MPH");
    break;

使用此功能(空气代码,需要错误处理):

string GetNumericInput(string prompt)
{
    Console.WriteLine(prompt;
    string input = Console.ReadLine();
    int inputNumeric = int.Parse(input);
    return input;
}

答案 2 :(得分:0)

你可以删除一个if语句,它与其他if语句不同。用这个替换它:

        if (Calculation < 1 || Calculation > 3)
        {
            Console.WriteLine("Please enter a number greater than or equal to 1 but less than 3.");
        }

创建两个函数以返回用户输入一个用于int,第二个用于双返回类型。

    private int GetIntUserInput()
    {
        string userInput = Console.ReadLine();
        int convertedUserInput = int.Parse(userInput);

        return convertedUserInput;
    }

    private double GetDoubleUserInput()
    {
        string userInput = Console.ReadLine();
        double convertedUserInput = double.Parse(userInput);

        return convertedUserInput;
    }

我也应该将计算转移到功能上 您还可以使用枚举来提高可读性。

    enum Options
    {
        Speed,
        Time,
        Distance
    } 

     //example
      Options calculation = (Options)Calculation; //cast user input number 
                                                  // to Option enum 
      switch (calculation)
      {
       case options.Distance:
           // some code
       break;
       case options.Speed:
           // some code
       break;
      }

答案 3 :(得分:0)

我通常的组织代码的方法是将每个案例组成一个类,然后根据案例值将这些类添加到字典中,例如:

public interface ICalculation
{
    void Run();
}

public class SpeedCalculation
    : ICalculation
{
    public void Run()
    {
        Console.WriteLine("You have chose to calculate speed. S = D/T");

        Console.WriteLine("To work this out you need to firstly enter your distance in metres");
        string userDistance = Console.ReadLine();
        int Distance = int.Parse(userDistance);

        Console.WriteLine("Now enter your time in seconds.");
        string userTime = Console.ReadLine();
        int Time = int.Parse(userTime);

        Console.WriteLine("Your speed is " + Distance / Time + " m/s");
        Console.WriteLine("In MPH this is " + Distance / Time * 2.23 + "MPH");
    }
}

...more ICalculation types...

class Program
{
    static void Main(string[] args)
    {
        var caseDictionary = new Dictionary<int, ICalculation>
        {
            {1, new SpeedCalculation()},
            {2, new DistanceCalculation()},
            {3, new TimeCalculation()}
        };

        Console.WriteLine("This is a system to calculate speed, distance or time.");
        Console.WriteLine("1 = Speed - 2 = Distance - 3 = time");
        Console.WriteLine("Please enter which calculation you would like to perform. 1, 2 or 3");

        string userCalculation = Console.ReadLine();
        int Calculation = int.Parse(userCalculation);

        if(!caseDictionary.ContainsKey(Calculation))
        {
            Console.WriteLine("Please enter a number between 1 and 3 (inclusive).");
        }
        else
        {
            caseDictionary[Calculation].Run();
        }
    }
}

这为您提供了使用继承或抽象组织代码的选项,可以轻松添加新案例(甚至以编程方式),并且可以使主方法更灵活(例如,行“1 = Speed - 2 =距离 - 3 =时间“可以从字典的内容生成。”

答案 4 :(得分:0)

我会做以下事情:

class Program
{
    private class MenuOption
    {
        public string Description { get; }
        public Action Run { get; }

        public MenuOption(string description, Action run)
        {
            Description = description;
            Run = run;
        }
    }

    static void Main(string[] args)
    {
        int option;
        var menuOptions = buildMenuOptions();

        do
        {
            Console.WriteLine($"This is a system to calculate: {string.Join(", ", menuOptions.Values.Take(menuOptions.Count-1).Select(o => o.Description))}");
            Console.WriteLine(string.Join(" - ", menuOptions.Select(kv => $"{kv.Key} = {kv.Value.Description}")));
            Console.WriteLine($"Please enter which calculation you would like to perform. [{string.Join(", ", menuOptions.Keys)}]");
        } while (!tryValidateUserOption(menuOptions, out option));

        menuOptions[option].Run();
        Console.Write("Press key to exit... ");
        Console.ReadKey();
    }

    private static IDictionary<int, MenuOption> buildMenuOptions() =>
        new Dictionary<int, MenuOption>() { { 1, new MenuOption("Speed", () => runSpeedOption()) },
                                            { 2, new MenuOption("Distance", () => runDistanceOption()) },
                                            { 3, new MenuOption("Time", () => runTimeOption())},
                                            { 4, new MenuOption("Quit", () => { return; }) } };

    private static bool tryValidateUserOption(IDictionary<int, MenuOption> options, out int selectedOption)
    {
        var input = Console.ReadLine();

        if (!int.TryParse(input, out selectedOption) ||
            !options.ContainsKey(selectedOption))
        {
            Console.WriteLine("Invalid option. Please try again.");
            return false;
        }

        return true;
    }

    private static void runTimeOption()
    {
        int miles;
        double speed;
        Console.WriteLine("You have chose to calculate Time. T = D/S.");
        getUserInput("To work this out you need to firstly enter your distance in miles.", 0, int.MaxValue, out miles);
        getUserInput("Now enter your Speed in MPH.", 0, double.MaxValue, out speed);
        Console.WriteLine("Your Time is " + miles / speed + " hours.");
        Console.WriteLine("This would be " + miles / speed * 60 + " minutes");
    }

    private static void runDistanceOption()
    {
        int speed;
        double time;
        Console.WriteLine("You have chose to calculate distance. D = SxT.");
        getUserInput("To work this out you need to firstly enter your speed.", 0, int.MaxValue, out speed);
        getUserInput("Now enter your time in hours.", 0, double.MaxValue, out time);
        Console.WriteLine("Now enter your time in hours.");
        Console.WriteLine("Your Distance is " + speed * time + " miles");
    }

    private static void runSpeedOption()
    {
        int distance, time;
        Console.WriteLine("You have chose to calculate speed. S = D/T");
        getUserInput("To work this out you need to firstly enter your distance in metres.", 0, int.MaxValue, out distance);
        getUserInput("Now enter your time in seconds.", 0, int.MaxValue, out time);
        Console.WriteLine("Your speed is " + distance / time + " m/s");
        Console.WriteLine("In MPH this is " + distance / time * 2.23 + " MPH");
    }


    private static void getUserInput(string message, int lowerInclusiveBound, int upperExclusiveBound, out int value)
    {
        while (true)
        {
            Console.WriteLine(message);
            var input = Console.ReadLine();

            if (int.TryParse(input, out value) &&
                value >= lowerInclusiveBound &&
                value < upperExclusiveBound)
                return;

            Console.WriteLine("Input is not a valid value. Please try again.");
        }
    }

    private static void getUserInput(string message, double lowerInclusiveBound, double upperExclusiveBound, out double value)
    {
        while (true)
        {
            Console.WriteLine(message);
            var input = Console.ReadLine();

            if (double.TryParse(input, out value) &&
                value >= lowerInclusiveBound &&
                value < upperExclusiveBound)
                return;

            Console.WriteLine("Input is not a valid value. Please try again.");
        }
    }
}

注意事项:

  1. 不要对菜单进行硬编码。使其变得灵活,这样就可以轻松添加选项;看看添加第四个选项需要多少。
  2. 如果未设置菜单,则无法使用ifs和开关硬编码选项。使用带有选项编号的字典作为键。将值存储为您要执行的操作的委托。
  3. 尽量不重复代码。将所有常用功能提取到可以重用的辅助方法;考虑将所有输入更改为double,以减少验证int和double的麻烦代码重复。