Error whilst using StringTokenizer on text file with multiple lines

前端 未结 4 1238
我在风中等你
我在风中等你 2021-01-07 11:11

I\'m trying to read a text file and split the words individually using string tokenizer utility in java.

The text file looks like this;

a 2000

4  
b         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-07 11:56

    This problem is due to the fact that you don't test if there is a next token before trying to get the next token. You should always test if hasMoreTokens() before returns true before calling nextToken().

    But you have other bugs :

    • The first line is read, but not tokenized
    • You only add the first word of each line to your list of words
    • bad practice : the token variable should be declared inside the loop, and not outside
    • you don't close your reader in a finally block

提交回复
热议问题