1

I used Tokenizer to split a text file which was separated like so:

FIRST NAME, MIDDLE NAME, LAST NAME

harry, rob, park

tom,,do

while (File.hasNext()) 
    {
        StringTokenizer strTokenizer = new StringTokenizer(File.nextLine(), ",");

        while (strTokenizer.hasMoreTokens())
        {

I have used this method to split it.

The problem is that when there is missing data (for example Tom does not have a middle name) it will ignore the split (,) and register the next value as the middle name.

How do I get it to register it as blank instead?

Axelotl
  • 13
  • 2

4 Answers4

0

Use String.split instead.

"tom,,do".split(",") will yield an array with 3 elements: tom, (blank) and do

Davio
  • 4,609
  • 2
  • 31
  • 58
0

Seems to me like you have 2 solutions:

  • You either double the comma in the file as suggested by ToYonos OR.
  • You can count the tokens before you assign the values to the variables using the countTokens() method, if there are only 2 tokens that means the person doesn't have a middle name.
Community
  • 1
  • 1
Iootu
  • 344
  • 1
  • 6
0

based on Davio's answer you can manage the blank and replace it with your own String :

String[] result = File.nextLine().split(",");
for (int x = 0; x < result.length; x++){
    if (result[x].isEmpty()) {
    System.out.println("Undefined");
    } else
    System.out.println(result[x]);
}
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
0

From JavaDoc of StringTokenizer

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead

So, you don't need the use of StringTokenizer.

An example with String.split

String name = "name, ,last name";
String[] nameParts = name.split(",");
for (String part : nameParts) {
    System.out.println("> " + part);
}

this produces the following output

> name
>  
> last name
vzamanillo
  • 9,905
  • 1
  • 36
  • 56