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:
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!