简体   繁体   中英

Getting a Method in the Main C#

     static void bubble(int [] mas)
    {
        int temp;
        for (int i = 0; i < mas.Length; i++)
        {
            for (int j = 0; j < mas.Length - 1; j++)
                if (mas[j] > mas[j + 1])
                {
                    temp = mas[j + 1];
                    mas[j + 1] = mas[j];
                    mas[j] = temp;
                }

        }
        foreach (var element in mas)
        {
            Console.WriteLine("Sorted elements are: {0}", element);

        }

    }

    static void Main(string[] args)
    {
        int[] mas = new int[5];
        Console.WriteLine("Please enter the elements of the array: ");
        for (int i = 0; i < 5; i++)
        {
            mas[i] = Convert.ToInt32(Console.ReadLine());
        }
        bubble();
    }

I need to be using methods to solve some tasks for Uni project and the problem I am having is that I want to create an array in the Main, use it in different methods and call the results of those methods back to the Main. When I do that and try and call the "bubble" back in to the Main it is telling me that there is no argument given that corresponds to the formal given parameter. Is there an easy way to fix that so I can fix that and proceed in creating the other methods analogically. Thanks in Advance

The reason you are getting the error is because the function bubble requires an int[] as a parameter.

Currently you have bubble() which in its current state is "parameterless"

Replace it with bubble(mas);

您需要在main的Bubble调用中传递参数:

bubble(mas);

change your code like this :

static int[] bubble(int [] mas)
    {
        int temp;
        for (int i = 0; i < mas.Length; i++)
        {
            for (int j = 0; j < mas.Length - 1; j++)
                if (mas[j] > mas[j + 1])
                {
                    temp = mas[j + 1];
                    mas[j + 1] = mas[j];
                    mas[j] = temp;
                }

        }
        foreach (var element in mas)
        {
            Console.WriteLine("Sorted elements are: {0}", element);

        }

    }

    static void Main(string[] args)
    {
        int[] mas = new int[5];
        Console.WriteLine("Please enter the elements of the array: ");
        for (int i = 0; i < 5; i++)
        {
            mas[i] = Convert.ToInt32(Console.ReadLine());
        }
        bubble(mas);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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