In: Computer Science
FOR JAVA
Write a method called findNum that takes a two-dimension array of integers and an int as parameters and returns the number of times the integer parameter appears in the array.
For example, if the array (as created by the program below) is
10 45 3 8
2 42
3 21 44
And the integer parameter is 3, the value returned would be 2 (the number 3 appears two times in the array)
public class HomeworkA {
public static void main(String args[]){
int arr[][] = {{10, 45, 3, 8}, {2, 42}, {3, 21, 44}};
System.out.println(“The number time 3 appears is “+findNums(arr,3)); }
public static int findNum (int [][] myArray) {
..........
import java.util.*;
import java.io.*;
public class Occurrence
{
public static void main(String[] args)
{
int[][] arr={{10, 45, 3,8 },{ 2,42 },{3,21,44}};
//2D array arr, initialized with the above elements
System.out.println("The number of times 3 appearing is: "
+findNums(arr,3));
//a print statement, which calls the findNums()
//it passes arr and counting number 3
//It prints the value returned by the method
}//end of main()
public static int
findNums(int [][] myArray,int num)
{
int count=0;
//count=0, to count the occurrence
of the number
for(int i = 0; i <
myArray.length; i++)
{
//outer loop to set to length of the
2D array limit
//That is the
rows
for (int j = 0; j < myArray[i].length; j++)
{
//inner loop is set to columns limit
if(myArray[i][j]==num)
//checking each position element is match with the num value
//here, the num value holds value 3
//if it matches, just increment the count variable
count++;
}//end of loop
}//end of outer
loop
return count;
//return count value to main
}//enof method
}//end of class
Screenshot