Search code examples
stringstringtokenizer

StringTokenizer returns null instead of String


The segment of code is meant to take a line of text pulled from a text file, separate it into separate tokens, and store each token in an index of an array. At first I thought the problem was with the text file, but putting the string into the editor directly didn't fix it.

With a string such as :

"Chicken|None|Beast|Any|0|1|1|Hey Chicken!"

a StringTokenizer object with delimiter | returns the first four tokens as proper Strings, but null for the remaining four.

Interestingly enough, another String :

"Gnoll|None|General|Any|2|2|2|Taunt|Taunt"

Will return the first five tokens as proper strings, but null for the remaining four as well.

If the problem is with the final four tokens, why is the StringTokenizer returning nulls in this fashion?

Code:

String[] parameter = new String[10];
String rawTxt = "Chicken|None|Beast|Any|0|1|1|Hey Chicken!";
StringTokenizer t = new StringTokenizer(rawTxt, "|");
for (int i = 0; i < t.countTokens(); i++) {
    parameter[i] = t.nextToken();
    System.out.print(parameter[i] + " ");
}

Output:

Chicken None Beast Any


Solution

  • StringTokenizer is deprecated so should use String split method and it works for you code

        import java.util.Arrays;
    
     public class MainClass {
        public static void main(String[] args) {
        String[] parameter = new String[10];
        String rawTxt = "Chicken|None|Beast|Any|0|1|1|Hey Chicken!";
        String[] split = rawTxt.split("\\|");
        System.out.println(Arrays.toString(split));
        }
    
    }