用c#表示用户可以输入数字的数组

时间:2014-11-06 22:31:44

标签: c# arrays algorithm sorting

我想让用户输入数字,然后用气泡排序对其进行排序,但我没有达到正确的实施方式:/

class bubblesort
{
    static void Main(string[] args)
    {
        int[] a = new int[5];
        int t;

        for (int p = 0; p <= a.Length - 2; p++)
        {               
            for (int i = 0; i <= a.Length - 2; i++)
            {
                if (a[i] > a[i + 1])
                {
                    t = a[i + 1];
                    a[i + 1] = a[i];
                    a[i] = t;
                }

                InputStudent(a[i]);
            }               
        }

        Console.WriteLine("The Sorted array");

        foreach (int aa in a)
        {
            Console.Write(aa + " ");
        }

        Console.Read();
    }

    static void InputStudent(int p)
    {
        Console.WriteLine("Enter the Number");

        p = int.Parse(Console.ReadLine());
        Console.WriteLine();
    }

    public static int i { get; set; }
}

1 个答案:

答案 0 :(得分:1)

您应该首先从用户那里获取数字,然后您可以对它们进行排序。现在你的InputStudent函数没有做任何事情 - 它只是将一个整数作为参数,用用户的值重新赋值,然后退出。

你可以改为做这样的事情来获取用户的一组int:

private static int[] GetIntArrayFromUser(int numberOfElementsToGet)
{
    var intArrayFromUser = new int[numberOfElementsToGet];

    for (int i = 0; i < numberOfElementsToGet; i++)
    {
        while (true)
        {
            // Prompt user for integer and get their response
            Console.Write("Enter an integer for item #{0}: ", i + 1);
            var input = Console.ReadLine();

            // Check the response with int.TryParse. If it's a valid int, 
            // assign it to the current array index and  break the while loop
            int tmpInt;
            if (int.TryParse(input, out tmpInt))
            {
                intArrayFromUser[i] = tmpInt;
                break;
            }

            // If we get here, we didn't break the while loop, so the input is invalid.
            Console.WriteLine("{0} is not a valid integer. Try again.", input);
        }
    }

    return intArrayFromUser;
}

然后你可以从Main调用这个方法来填充你的数组:

static void Main(string[] args)
{
    int[] a = GetIntArrayFromUser(5); // Get a five-element array

    // Insert your bubble-sort code here

    // Show the sorted array
    Console.WriteLine("The sorted array:");
    Console.WriteLine(string.Join(" ", a));

    Console.Read();
}