创建计数方法

时间:2016-03-16 20:15:15

标签: java

我正在尝试创建一个方法,您可以放入一个数组位置(如[b]),它将计算该元素的总数。这就是我想出的:

public static int getCount(double a[b])
    {
        int count;
        int Element;
        for(Element = 0; Element < a.length; Element++)
        {
            if(a[b] = a[Element])
            {
                return count++;
            }
        }
    }

但是,这不会编译。这是为什么?而且,这是获得数组某个元素总数的最有效方法吗?

3 个答案:

答案 0 :(得分:5)

您需要更改方法中的签名和引用:

// How many times is "d" in array "a"?
public static int getCount(double[] a, double d) {
    int count = 0;
    for(int e : a) {
        if(e == d) {
            count++;
        }
    }
    return count;
}

答案 1 :(得分:2)

使用

您可以使用+testgroup TEST_SERVER_LIST = (${LOGNAME}_test) ALL 并在过滤了流后返回DoubleStream的结果

count

答案 2 :(得分:1)

您需要将数组和数组元素的位置作为单独的参数发送到函数。最简单的解决方案是创建一个扩展方法,它将采用数组和方法。数组位置作为参数并返回该位置存在的元素的数量。

int[] a = new int[8]{1,2,3,4,5,3,6,3};
a.getCount(3);

static class Extension
{
    public static int GetCount(this Array arr, int position)
    {
        int count = 0;
        if(position < arr.Length)
        {
            var searchElement = arr.GetValue(position - 1);
            foreach(var element in arr)
            {
                if(searchElement.Equals(element))
                {
                    count++;
                }
            }
        }

        return count;
    }
} 

这里的好处是你可以为任何类型的数组调用这个函数。