[英]Calling a method to fill a 2d array in C#
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.我是一个非常新的程序员,并且一直在努力编写一个可以采用任何二维数组并用 1 到 15 之间的随机整数填充它的方法。我相信我成功地构建了我的方法,但我似乎看不到然后如何调用我的方法来填充我在 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.
(我会直接将它填入 main 中,但我也在尝试练习方法。)这是我目前拥有的代码。 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;
}
}
} }
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: 然后您可以使用以下命令从
Main
调用它:
FillArray(myArray);
Notes: 笔记:
Program
instance Program
实例的任何状态 Random
instance "on demand" is a bad idea; Random
实例不是一个好主意。 read my article on Random
for more details Random
文章以了解更多详细信息 Simple technique is to make the use of Enumberable.Repeat() in C#.简单的技术是在 C# 中使用 Enumerable.Repeat()。 Check below code for 5 column and 10 row mattrix.
检查以下 5 列和 10 行矩阵的代码。
int[][] a = Enumerable.Repeat(Enumerable.Repeat(-1, 5).ToArray(), 10).ToArray();
for(int i =0; i < a.Length; i++)
{
for(int j=0; j < a[0].Length; j++)
{
Console.Write($"{a[i][j]} \t");
}
Console.WriteLine();
}
O/p:
开/关:
-1 -1 -1 -1 -1
-1 -1 -1 -1 -1
-1 -1 -1 -1 -1-1 -1 -1 -1 -1
-1 -1 -1 -1 -1-1 -1 -1 -1 -1
-1 -1 -1 -1 -1-1 -1 -1 -1 -1
-1 -1 -1 -1 -1-1 -1 -1 -1 -1
-1 -1 -1 -1 -1-1 -1 -1 -1 -1
-1 -1 -1 -1 -1-1 -1 -1 -1 -1
-1 -1 -1 -1 -1-1 -1 -1 -1 -1
-1 -1 -1 -1 -1-1 -1 -1 -1 -1
-1 -1 -1 -1 -1-1 -1 -1 -1 -1
See it in action!看到它在行动!
https://rextester.com/SXU33123 https://rextester.com/SXU33123
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.