Rabiani
Rabiani

Reputation: 143

check to see if next String tokenizer is empty

I'm having a problem, I'm using a text file that has over a million lines of numbers. the data is in the format below, some lines have 3 pieces of data while others have only 2. Each time the file gets to the data with only 2 bits, it seems to throw a null error (I'm using Try/catch to read the input stream)

If I remove the value 3 tokenizer then the program runs to the end. Do I need to put an if statement to check if there is another token after the 2nd line? if so - how??

            while ((getLine = br.readLine()) != null)   {
              StringTokenizer tokenizer = new StringTokenizer(getLine);
              String Value1 = tokenizer.nextToken();
              String Value2 = tokenizer.nextToken();
              String Value3 = tokenizer.nextToken();
            //Does some more things
            }

The data

    11      22      33
    44      55      
    77      88      99
    10      11
    13      14
    16      17      18

Upvotes: 1

Views: 8098

Answers (3)

LearningDeveloper
LearningDeveloper

Reputation: 668

Well, how about using a try catch block like this..?

String Value1 = null, Value2 = null, Value3 = null;

try {
    Value1 = null;
    Value2 = null;
    Value3 = null;

    Value1 = tokenizer.nextToken();
    Value2 = tokenizer.nextToken();
    Value3 = tokenizer.nextToken();
} catch (NoSuchElementException nse) {
    // Do Nothing. Just continue..
}
// Does some more things

System.out.println(Value1 + Value2 + Value3);

You'll have a null "Value" if at all any token is not read.

Upvotes: 0

moinudin
moinudin

Reputation: 138357

You will have to check that there are still tokens in the tokenizer. You can do it like this:

String Value3 = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;

Which will set Value3 to null if there is no 3rd token. You might want to instead set it to the empty string.

The alternative is to use getLine.split("\\s+"), which will return an array of tokens. If there are only 2 values, the array will be of length 2. So be careful when attempting to read the 3rd value, which might not be present.

Upvotes: 6

blackcompe
blackcompe

Reputation: 3190

If you try call nextToken a third time, when no token exists, it returns null. A better thing to do is to use String.split, where you can check the number of tokens. StringTokenizer is legacy anyway.

String[] tokens = getLine.split("\\s+");

Upvotes: 0

Related Questions