简体   繁体   English

在主C#中获取方法

[英]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. 我需要使用方法来解决Uni项目的某些任务,而我遇到的问题是我想在Main中创建一个数组,在其他方法中使用它,然后将这些方法的结果返回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. 当我这样做并尝试将“气泡”重新调用到Main时,它告诉我没有给定的参数与形式上给定的参数相对应。 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. 出现错误的原因是因为函数bubble需要int[]作为参数。

Currently you have bubble() which in its current state is "parameterless" 当前,您有bubble() ,其当前状态为“无参数”

Replace it with bubble(mas); bubble(mas);代替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);
    }

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

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