我目前必须编写一个接受两个参数的方法:一个名为 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/