编写一个Java类,它具有一个名为count的静态方法,它接受一个2D整数数组和一个目标整数值作为参数,并返回数组中目标值的出现次数。例如,如果名为list的变量引用包含值{{3,5,7,94}{5,6,3,50}}
的数组,则count(list, 3)
的调用应返回2,因为数组中有2次出现值3。
这是我的编码,它没有给我正确的输出P.S: - 我被告知采取计数方法公共而非静态
class java
{
public int count(int [,] list,int n)
{
int c = 0;
for (int i = 0; i <list.Length; i++)
{
for (int j = 0; j < list.Length; j++)
{
if (list[i, j] == n)
{
c++;
}
}
}
return c;
}
class Program
{
static void Main(string[] args)
{
java jv = new java();
int[,] arr = { { 3, 5, 7, 94 }, {5, 6, 3, 50 } };
int k=0;
jv.count(arr,k);
}
}
迭代多维数组需要您使用自己的长度迭代每个维度,这意味着i
和j
应分别为0-3
和0-1
。
从图中可以看出,但对于不同尺寸的数组:
GetLength(0)
将返回4。
GetLength(1)
将返回3。
当你在i = (0 to Length)
= 8时j = (0 to Length)
超过Length = Height * Width
时,你正在做的是迭代它们,这意味着8超过8。
所以你的count()
方法应该是这样的:
public int count(int[,] list,int n)
{
int c = 0;
for (int i = 0; i < list.GetLength(0); i++)
{
for (int j = 0; j < list.GetLength(1); j++)
{
if (list[i, j] == n)
{
c++;
}
}
}
return c;
}
如果你想将数组迭代为一个数组数组而不是让事情变得复杂“我现在正在迭代哪个维度?”你可以使用Jagged Arrays(当然还有更多的事情需要考虑),这将允许你用这个短的Linq
替换整个方法:
public int count(int[][] list,int n)
{
return list.SelectMany(x => x).Count(x => x == n);
}
要么:
public int count(int[][] list, int n)
{
return list.Sum(x => x.Count(y => y == n));
}
注意i在内部for
中对抗j。并且使用i <list.GetLength(0)
和j < list.GetLength(1)
对抗list.Length
class java
{
public int count(int [,] list,int n)
{
int c = 0;
for (int i = 0; i < list.GetLength(0); i++)
{
for (int j = 0; j < list.GetLength(1); j++)
{
if (list[i, j] == n)
{
c++;
}
}
}
return c;
}
class Program
{
static void Main(string[] args)
{
java jv = new java();
int[,] arr = { {3,5,7,94 }, {5,6,3,50 } };
int k=5;
Console.WriteLine(jv.count(arr,k));
}
}
由于Array
已经实现了IEnumerable
,你可以在这里简单地使用foreach循环(随意将static更改为实例方法):
public static int count(int[,] list, int n)
{
int c = 0;
foreach (var item in list) if (item == n) c++;
return c;
}
用法:
static void Main()
{
var r = count(new int[,]{
{
5, 8, 7, 8
},
{
0, 8, 9, 3
}}, 8);
Console.WriteLine(r);
输出:3
附:通常如果可能的话,最好使用for
循环,因为它比foreach
快,但在这种情况下我喜欢,如果你使用foreach你没有嵌套的for
循环也没有GetLength(x)调用它只是一行代码和它几乎具有相同的性能......
你的错误在这一行:
for (int j = 0; i < list.Length; j++)
它应该是
for (int j = 0; j < list.Length; j++)