如何在方法中声明数组[重复]

时间:2021-07-20 01:20:56

This question already has an answer here:

这个问题在这里已有答案:

I am currently having to write a method that takes in two parameters: an array of integers called data and an integer called num. The purpose of this method is to count the amount of times that number shows up in the array. I am having trouble figuring out how to declare the array in the method. I was wondering if there was any easier way that I did below:

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

Method

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.");
}

Main Class

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

So I was wondering if you could directly declare the array within the countNumbers(data,num) any help would be appreciated!

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

1 个解决方案

#1


2  

Is that what you are looking for?

这是你在找什么?

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

#1


2  

Is that what you are looking for?

这是你在找什么?

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