Advertisement
Guest User

functions homework

a guest
Aug 20th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.99 KB | None | 0 0
  1. public class FunctionsHW {
  2.  
  3.     /*
  4.     q1-1
  5.     this method find the number of instances of a digit in a number
  6.      */
  7.     public static int numOfInstances(int a, int numToFind) {
  8.         int counter = 0;
  9.         while (a > 0) {
  10.             if (a % 10 == numToFind) {
  11.                 counter += 1;
  12.             }
  13.             a /= 10;
  14.         }
  15.         return counter;
  16.     }//end of numOfInstances
  17.  
  18.     /*
  19.     q1-2
  20.     this method find the number of instances of a digit in array
  21.     by using method numOfInstances
  22.      */
  23.     public static int arrInstances(int[] array, int numToFind) {
  24.         int counter = 0;
  25.         for (int i = 0; i < array.length; i += 1) {
  26.             counter += numOfInstances(array[i], numToFind);
  27.         }
  28.         return counter;
  29.     }//end of arrInstances method
  30.  
  31.     /*
  32.     q2
  33.     this method takes two arrays and return a new array
  34.     with the similar values of the two given arrays
  35.      */
  36.     public static int[] similarValues(int[] arr1, int[] arr2) {
  37.         int[] similarArray = new int[(arr1.length + arr2.length) / 2];
  38.         for (int i = 0; i < arr1.length; i += 1)
  39.             for (int j = 0; j < arr2.length; j += 1) {
  40.                 if (arr1[i] == arr2[j])
  41.                     similarArray[i] = arr1[i];
  42.             }
  43.         return similarArray;
  44.     }
  45.  
  46.     /*
  47.     added a method to print the array
  48.      */
  49.     public static String printArray(int[] arr) {
  50.         String array = "";
  51.         for (int i = 0; i < arr.length; i += 1)
  52.             if (arr[i] != 0)
  53.                 array += arr[i] + "\t";
  54.  
  55.         return array;
  56.     }
  57.  
  58.  
  59.     //main
  60.     public static void main(String[] args) {
  61.         int[] array1 = {33, 2, 3, 4, 55, 66, 64, 63, 6};//6 appears 5 times
  62.         int[] array2 = {3, 4, 66, 7, 8, 9, 10, 11, 12}; // 3,4,66
  63.  
  64.         System.out.println(numOfInstances(1222344, 2));
  65.         System.out.println(arrInstances(array1, 6));
  66.         System.out.println(printArray(similarValues(array1, array2)));
  67.     }//end of main
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement