About the findNeedles() Method

The findNeedles() method as provided (I came to realize) is not very efficient. Note that the text comprising the haystack in findNeedles() is tokenized into an array for each new word search.

Along with many other changes to the original method, reorganized the loops for better efficiency (and basic logic) so that the needles array drives the for... loop to searching through the array of text (haystack), which in my revised code is created one time only.

Here is 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]);
		}
}
}


In addition to the required main() method, I added the checkEntry() method shown below to check the value input by the user before invoking findNeedles, so error handling occurs before the findNeedles() method is ever invoked.

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


My revised findNeedles() method is 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]);
    }
}


See the Java code for NeedlesHaystackTest for complete code context.