I've written code that has to use a StringTokenizer and split the input string into parts based on the delimiter variable, while the maximum possible number of tokens must be 6. The result must be returned without null tokens. I guess I've done all that and my code produces the required output. What exactly am I still missing?
package en.codegym.task.pro.task09.task0915;
import java.util.Arrays;
import java.util.StringTokenizer;
/*
StringTokenizer
String str = "Good news everyone!";
StringTokenizer tokenizer = new StringTokenizer(str,"ne");
while (tokenizer.hasMoreTokens())
{
String token = tokenizer.nextToken();
System.out.println(token);
}
*/
public class Solution {
public static void main(String[] args) {
String packagePath = "java.util.stream";
String[] tokens = getTokens(packagePath, "\\.");
System.out.println(Arrays.toString(tokens));
}
public static String[] getTokens(String query, String delimiter) {
//write your code here
//first we create a tokenizer
StringTokenizer tokenizer = new StringTokenizer(query, delimiter);
/*
acording to the task conditions, the maximum possible number of tokens is 6;
so we create an array of six null strings that we'll fill with values later
*/
String[] arrayOfSix = new String[6];
int countNullTokens = 0; //this is the number we'll need later to get the right length of the array to return
for (int i = 0; i < 6; i++) {
if (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
arrayOfSix[i] = token;
}
else {
countNullTokens++;
}
}
/*if our method returned arrayOfSix as it is,
the output would be [java, util, stream, null, null, null].
So we need another array, shorter than arrayOfSix by the number of null tokens*/
String[] arrayResult = Arrays.copyOf(arrayOfSix, (6 - countNullTokens));
return arrayResult;
}
}