简体   繁体   English

C# 我想使用 switch 或 if 语句来 select 排序算法

[英]C# I want to use either a switch or if statement to select a sorting algorithm

I am writing a program that will take user input and run it through whichever type of sort they choose.我正在编写一个程序,它将接受用户输入并通过他们选择的任何类型的排序来运行它。 If I try to use a switch I cannot figure out how to add arguments to a switch or if I use an if statement how do I implement that with the user's input?如果我尝试使用开关,我无法弄清楚如何将 arguments 添加到开关,或者如果我使用 if 语句,我该如何通过用户输入实现它?

Here is the code and thank you all for your help.这是代码,谢谢大家的帮助。

using System;

namespace ASortAboveTheRest
{
    internal class Program        
    {
        static void Main(string[] args)
        {
            MainMenu();
        }

        static void MainMenu()
        {
            Console.Clear();
            Console.WriteLine("Choose a sort algorithm to perform on the Array");
            Console.WriteLine("");
            Console.WriteLine("Option 1: Heap Sort");
            Console.WriteLine("Option 2: Bubble Sort");
            Console.WriteLine("Option 3: Shell Sort");

            Console.WriteLine("Please type: 1, 2, or 3");
            string myOption;
            myOption = Console.ReadLine();
            int[] arr = new int[10];
            int i;
            Console.Write("Input 10 elements in the array :\n");
            for (i = 0; i < 10; i++)
            {
                Console.Write("element - {0} : ", i);
                arr[i] = Convert.ToInt32(Console.ReadLine());
            }            

            Console.Write("\nElements in array are: ");
            for (i = 0; i < 10; i++)
            {
                Console.Write("{0}  ", arr[i]);
            }
            Console.Write("\n");
            ...
        }
    }
}

The following code should do the trick: using System;下面的代码应该可以解决问题:using System;

namespace ASortAboveTheRest { 
    internal class Program
    {
        static void Main(string[] args)
        {
            MainMenu();
        }

        static void MainMenu()
        {    
            Console.Clear();
            Console.WriteLine("Choose a sort algorithm to perform on the Array");
            Console.WriteLine("");
            Console.WriteLine("Option 1: Heap Sort");
            Console.WriteLine("Option 2: Bubble Sort");
            Console.WriteLine("Option 3: Shell Sort");

            Console.WriteLine("Please type: 1, 2, or 3");
            // Take Option input as an INT
            int myOption;
            myOption = Convert.ToInt32(Console.ReadLine());

            int[] arr = new int[10];
            int i;
            Console.Write("Input 10 elements in the array :\n");
            for (i = 0; i < 10; i++)
            {
                Console.Write("element - {0} : ", i);
                arr[i] = Convert.ToInt32(Console.ReadLine());
            }

            Console.Write("\nElements in array are: ");
            for (i = 0; i < 10; i++)
            {
                Console.Write("{0}  ", arr[i]);
            }
            Console.Write("\n");
            
            //Use switch case after taking array input from the user
            switch(myOption) {
            case 1:
                //Call Heap Sort Function and pass your array
                break;
            case 2:
                // Call Bubble Sort Function and pass your array
                break;
            case 3:
                //Call Shell Sort Function and pass your array
                break;
            default:
                break;
            }
        }
    }
}

You shall:你应该:

  1. read the option as a string and then try to parse it, handling the mistake of conversion将选项作为字符串读取,然后尝试解析它,处理转换错误
  2. also handle cases when a user enters a number that doesn't match your options还处理用户输入的数字与您的选项不匹配的情况
  3. rule of thumb: never use 'if' you can use 'switch', never used 'switch' if the mapping can be specified as a dictionary经验法则:永远不要使用'if'你可以使用'switch',如果映射可以指定为字典则永远不要使用'switch'
string optionTyped = Console.ReadLine();
int sortOption = Convert.ToInt32(Console.ReadLine());
var sortFunctions = new Dictionary<int, Func<int[], int[]>>
    {
        { 1, HeapSort },
        { 2, BubbleSort },
        { 3, ShellSort }
    };
    
while(!Int32.TryParse(optionTyped, out sortOption)
      or (!sortFunctions.Keys.Contains(sortOption)))
{
    Console.WriteLine("Not a valid option, try again.");
    optionTyped = Console.ReadLine();
}

Func<int[], int[]> sort = sortFunctions[sortOption]
...
int[] resultArray = sort(inputArray)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM