About the findNeedles() Method

The original findNeedles() method was not very efficient. For example, the text comprising the haystack in findNeedles() was tokenized into an array for each new word search, as shown below in the original findNeedles() method:


public static void findNeedles(String haystack, String[] needles) {
if(needles.length > 5) {
  System.err.println("Too many words!");
  }

else {
  int[] countArray = new int[needles.length];
  for(int i = 0; i < needles.length; i++) {
    String[] words = haystack.split("[ \"\'\t\n\b\f\r]", 0);
    for(int j = 0; j < words.length; j++) {
      if(words[j].compareTo(needles[i]) == 0) {
        countArray[i]++;
        }
      }
    }

  for (int j = 0; j < needles.length; j++) {
    System.out.println(needles[j] + ": " + countArray[j]);
		}
  }
}

For more efficicient processing, I changed the logic so that an array of text (haystack) is created only once, with the array of needles controlling the search in the for... loop, as shown below:


public static void findNeedles(String haystack, String[] needles) {
int[] counter = new int[needles.length];
String[] words = haystack.toLowerCase().split("[ .,:;\"\'\t\n\b\f\r]", 0);
for (int i = 0; i < needles.length; i++) {
   for (int j = 0; j < words.length; j++) {
      if (needles[i].equals(words[j])) {
        counter[i]++;
        }
      }
  }
for (int j = 0; j < needles.length; j++) {
    System.out.println(needles[j] + ": " + counter[j]);
    }
}

To ensure that findNeedles() would only be invoked with valid integer values, I added a checkEntry() method that prompts the user to re-enter valid data when necessary:


public static boolean checkEntry(int[] validEntries, int valueToCheck) {
boolean test = false;
for (int element : validEntries) {
  if (element == valueToCheck) {
    test = true;
    }
  }
  return test;
}


Several other changes were made to provide a complete running console application (for example, adding the main() method to instantiate the class). See the NeedlesHaystackTest.java doc or NeedlesHaystackTest.java source file. Java code for NeedlesHaystackTest for complete code.

Last updated 31 March 2020