Stefan Evans wrote:Putting the try/catch statements in is the correct thing to do.
Where have you put your text file you are trying to read?
When you run the program in your IDE it isn't finding the text file.
My suggestion: Find out where it THINKS the file should be.
That will tell you exactly where it is looking for the file to open.
Two ways to fix it
- Move the file to where it is 'expected' to be
- Specify a directory for the file as well as a filename to tell it exactly where you want it (remember you will need to escape \ characters in a java string)
So it might be:
Which I learnt from one of the other mods.
Earlier, I wrote: . . . the cheat's technique. . . .
Campbell Ritchie wrote:Welcome to the Ranch
Have you been told to use tokenizer; it is legacy code and not recommended for use in new code? Do you want the semicolon as well as the comma in the delimiter on line 22? I would use String#split there:-
String words = line.split(",");
You can get the number of tokens from the length of that array.
The Exception you are getting is caused by there not being as many lines in the file as you thought. The problem is that you are using the BufferedReader way to read lines and the Scanner way to read lines is different:-What was happening was that you were continuing to read beyond the end of the file. The Scanner won't return null, as a BufferedReader does; it throws an Exception. You need to use the hasNextXXX methods.
There is a simpler way to count tokens with a Scanner.