如何在方法中声明数组

时间:2017-04-07 01:03:35

标签: java arrays

我目前要编写一个接受两个参数的方法:一个名为data的整数数组和一个名为num的整数。此方法的目的是计算数字在数组中显示的次数。我无法弄清楚如何在方法中声明数组。我想知道下面是否有更简单的方法:

方式

public static void countNumbers( int data[], int num ) {
        int count = 0;

        for(int i = 0; i < data.length; i++) {
            if(data[i] == num)
                count++;
        }
        if (count == 0)
            System.out.println("There are no " + num + "'s in the array.");
        if (count == 1)
            System.out.println("There is one " + num + " in the array.");
        if (count > 1)
            System.out.println("There are: " + count + " " + num + "'s in the array.");
}

主要类

public static void main(String args[]) {
        int firstArray[] = {1,2,3,4,5};
        Methods.countNumbers(firstArray, 2);
    }

所以我想知道你是否可以在countNumbers(data,num)内直接声明数组,任何帮助都会受到赞赏!

1 个答案:

答案 0 :(得分:2)

这就是你要找的东西吗?

    <style> 
* {
margin:0;
padding:0 
}
</style>