java - 如何在方法中声明数组

标签 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) 中声明数组任何帮助将不胜感激!

最佳答案

这就是你要找的吗?

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

关于java - 如何在方法中声明数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43268071/

相关文章:

arrays - 使用 Any/AnyObject 的嵌套数组

c++ - C++ 解析器源代码中的无法解释的错误

java - Java 发生了什么变化,导致教程示例不再准确?

java - 在 JPanel 中使用 GlassPane

java - Spring 4 中 Websockets 的自定义对象映射器

javascript - 为什么我可以将命名属性添加到数组中,就好像它是一个对象一样?

javascript - 从循环中的值创建一个新数组,然后对新数组中的所有值求和

javascript - 我可以使用嵌套排序()对嵌套数组进行排序吗?

java - 从android方法中获取参数

java - 在不使用 BigInteger 的情况下处理 Java 中的溢出