Complete the method named countOccurs in the class named Arr
Complete the method, named countOccurs, in the class named ArrayOps.java. There are two parameters to this method: the first is an integer array, and the second parameter is a single integer.
This method counts the number of occurrences of the given integer (second) parameter within the array of integers. This integer count is the return value. For example, if the array contains four integers: 23, 31, 17, 23, and the second parameter is the value 23, then the value returned would be 2, as 23 occurs twice within that array. However, if the second parameter is the value 42, the value returned would be zero, as the array does not contain the integer 42.
Complete the following code:
Solution
public class ArrayOps {
/**
* This method goes through the array of integers identified by the first
* parameter, while counting the number of occurrences of the second
* parameter, a single integer, within the array.
*
* @param theArray
* , an array of integers
* @param theChar
* , an integer whose occurrences within the array need to be
* counted @ return, the count of the occurrences of the integer
* represented by the second parameter in the array of integers.
*/
public static int countOccurs(int[] theArray, int theInt) {
int count = 0;
// loop though theArray, counting occurrences of theInt
for (int i = 0; i < theArray.length; i++) {
if (theArray[i] == theInt)
count++;
}
// your work here
// return count of occurrences
return count;
// your work here
}
/**
* @param args
*/
public static void main(String[] args) {
int[] theArray = { 2, 1, 3, 4, 2 };
System.out
.println(\"number of time 2 elements is found in the array {2,1,3,4,2} is \"
+ countOccurs(theArray, 2));
}
}
OUTPUT:
number of time 2 elements is found in the array {2,1,3,4,2} is 2
