I checked for the edge case of more than 6 tokens and wrote test code to validate this. I return a non null String array, I am at a loss as to why I am not passing. It is not
the most efficient code but as far as I understand it meets the requirements.
package en.codegym.task.pro.task09.task0915;
import java.util.Arrays;
import java.util.StringTokenizer;
/*
StringTokenizer
*/
public class Solution {
public static void main(String[] args) {
// String packagePath = "java.util.stream.apache.maven.commons.org";
// String packagePath = "java.util.stream";
// String packagePath = "java.util";
// String packagePath = "java";
String[] data = {"java.util.stream.apache.maven.commons.org", "java.util.stream.apache.maven.org",
"java.util.stream.apache.maven", "java.util.stream.apache", "java.util.stream", "java.util", "java", ""};
// String[] data = {"Good news everyone!"};
for (String packagePath:data) {
String[] tokens = getTokens(packagePath, "\\.");
// String[] tokens = getTokens(packagePath, "ne");
System.out.println(Arrays.toString(tokens));
}
}
public static String[] getTokens(String query, String delimiter) {
final int maximumIndex = 5;
int count = 0;
String[] tokens = new String[6];
StringTokenizer tokenizer = new StringTokenizer(query, delimiter);
while (tokenizer.hasMoreTokens()) {
tokens[count] = tokenizer.nextToken();
count += 1;
if (count > maximumIndex) break;
}
count = 0;
for (String token:tokens) {
if (token != null) count++;
}
String[] finalTokenArray = new String[count];
for (int index = 0; index < finalTokenArray.length; index++) {
finalTokenArray[index] = tokens[index];
}
return finalTokenArray;
}
}