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

本文关键字:代码 方法 语句 Switch 是否 更简单 If | 更新日期: 2023-09-27 18:06:45

我的代码如下:

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;
            }
        }
    }
}
}

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

您可以删除一个if语句,它与其他if语句没有太大的区别。用这个替换:

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

创建两个函数返回用户输入,一个为int,另一个为double返回类型。

    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来提高可读性。

    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种算法分成单独的函数并调用它们,或者至少调用计算。
关于if/开关,您可以在开关的末尾使用default:大小写

default:
Console.WriteLine("Please enter a number greater than or equal to 1 but less than 3.");
break;

希望有帮助。

作为开始,也许像这样(air code):

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;

使用这个函数(air code,需要错误处理):

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

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

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 =速度- 2 =距离- 3 =时间"可以从字典的内容生成)。

我会这样做:

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. 如果菜单没有设置,你不能用If和开关硬编码选项。使用以选项号作为键的字典。将想要执行的操作的委托存储为值。
  3. 尽量不要重复代码。将所有常见功能提取到可重用的助手方法中;考虑将所有输入更改为double,以减少验证int型和double型的代码重复。