Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class FunctionsHW {
- /*
- q1-1
- this method find the number of instances of a digit in a number
- */
- public static int numOfInstances(int a, int numToFind) {
- int counter = 0;
- while (a > 0) {
- if (a % 10 == numToFind) {
- counter += 1;
- }
- a /= 10;
- }
- return counter;
- }//end of numOfInstances
- /*
- q1-2
- this method find the number of instances of a digit in array
- by using method numOfInstances
- */
- public static int arrInstances(int[] array, int numToFind) {
- int counter = 0;
- for (int i = 0; i < array.length; i += 1) {
- counter += numOfInstances(array[i], numToFind);
- }
- return counter;
- }//end of arrInstances method
- /*
- q2
- this method takes two arrays and return a new array
- with the similar values of the two given arrays
- */
- public static int[] similarValues(int[] arr1, int[] arr2) {
- int[] similarArray = new int[(arr1.length + arr2.length) / 2];
- for (int i = 0; i < arr1.length; i += 1)
- for (int j = 0; j < arr2.length; j += 1) {
- if (arr1[i] == arr2[j])
- similarArray[i] = arr1[i];
- }
- return similarArray;
- }
- /*
- added a method to print the array
- */
- public static String printArray(int[] arr) {
- String array = "";
- for (int i = 0; i < arr.length; i += 1)
- if (arr[i] != 0)
- array += arr[i] + "\t";
- return array;
- }
- //main
- public static void main(String[] args) {
- int[] array1 = {33, 2, 3, 4, 55, 66, 64, 63, 6};//6 appears 5 times
- int[] array2 = {3, 4, 66, 7, 8, 9, 10, 11, 12}; // 3,4,66
- System.out.println(numOfInstances(1222344, 2));
- System.out.println(arrInstances(array1, 6));
- System.out.println(printArray(similarValues(array1, array2)));
- }//end of main
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement