Calling a method to fill a 2d array in C#

南楼画角 提交于 2021-02-19 08:52:28

问题


I am a very new programmer, and have been struggling to write a method that can take any 2D array and fill it with random integers from 1 to 15. I believe I managed to build my method correctly, but I can't seem to see how to then call my method to fill the array I made in main. (I would have just filled it in main right out, but I'm trying to practice methods as well.) Here is the code I have so far. I appreciate any help you all are able to give me, thanks!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Homework2
{
class Program
{
    static void Main(string[] args)
    {
        int[,] myArray = new int[5,6];
    }

    public int[,] FillArray (int i, int j)
    {
        Random rnd = new Random();
        int[,] tempArray = new int[,]{};
        for (i = 0; i < tempArray.GetLength(0); i++)
        {
            for (j = 0; j < tempArray.GetLength(1); j++)
            {
                tempArray[i, j] = rnd.Next(1, 15);
            }
        }
        return tempArray;
    }
}

}


回答1:


Your method doesn't fill an array - it creates a new array. (It's also not at all clear what the parameters are meant to be for.)

If you want it to fill an existing array, you should have that as the parameter:

public static void FillArray(int[,] array)
{
    Random rnd = new Random();
    for (int i = 0; i < array.GetLength(0); i++)
    {
        for (int j = 0; j < array.GetLength(1); j++)
        {
            array[i, j] = rnd.Next(1, 15);
        }
    }
}

Then you can call it from Main with:

FillArray(myArray);

Notes:

  • We don't need to return anything, as the caller has already passed us a reference to the array to be filled
  • I've made the method static as it doesn't need to access any state of a Program instance
  • In general, creating a new Random instance "on demand" is a bad idea; read my article on Random for more details


来源:https://stackoverflow.com/questions/32618481/calling-a-method-to-fill-a-2d-array-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!