Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

StringTokenizer help

 
Jean Paul Martin
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I have a text file which I am having problem to read. Here is a sample.



here is my code:


However, I get these java.util.NoSuchElement error and nullpointer error all the time. Plus, I want to loop through and store all the data. Also, if you noticed, the last line in my sample text file above, Susan Little has no middle name and i do not know how to catch that because StringTokenizer will simple read the next token and put Little in the middlaName[] array.

I would really really appreciate your help. I know my code is very sloppy and i am looking for suggestions as to how to make it really efficient. Thank you and have a great day.

Jean Paul
 
Blake Minghelli
Ranch Hand
Posts: 331
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here are a couple of suggestions to hopefully get you moving...
1. Sun doesn't recommend you use StringTokenizer in new code. Use String.split() instead. And if you use the split(String regex, int limit) version, and specify -1 as the limit, it will return all tokens unlike the annoying StringTokenizer

2. Read through each line in your file using something like this:


3. What format is the file in? e.g. are the fields in each record (line) delimited by spaces (" "), tabs, or is it fixed-length? From your post, it looks like they are actually fixed-length. If so, then you might consider parsing the record into fields using String.substring(), like this:


4. To help debug your code, approach the code one step at a time. Your first step should be to perfect your record parsing code (e.g. using split() or substring()). You could do that by creating a simple "test" method something like this:
Then, once you got that perfected, try to throw in the file reading code. When in doubt, throw in as mush logging as you can - just simple System.out.println() calls can help diagnose problems.

Hope that helps. Good luck
 
Jean Paul Martin
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you so much for your great guidelines ... everything worked out great and i am moving forward with my application ... have a good one

Jean Paul
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic