• Post Reply Bookmark Topic Watch Topic
  • New Topic

NoSuchElementException inspite of using .hasNext()  RSS feed

 
Reddy Vivek
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to read data from a text file organized as columns, separated by tab spaces. As the parsing reaches the end of the file, the last value of the last row is not displayed and a NoSuchElementException is thrown. The last element in every column is displayed in a separate line.This is the Input Text File



 
Chan Ag
Rancher
Posts: 1090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Reddy Vivek, welcome to CodeRanch.

First your code is not formatted. Perhaps you'd like to format it and indent it properly so it is more readable.
And while coding, you should avoid writing more than 80 chars in a line including comments ( that is a good practice ).

Now coming to your question - how many tab separated values you have per logical record in your file and how many are you reading in one iteration of hasNext()?
Do you see a difference?

Also you might temporarily want to change the last System.out.println(....) statement as follows to see if you are reading the values correctly.



Edit : I have formatted your code and broken extremely long lines into shorter ones. No other thing was changed. In future you might want to do it yourself.


 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Reddy. Welcome to the Ranch!

It looks like you're using a Scanner to split on tabs...but nothing to split on new lines. So the first time you try to read the last column, you actually get the last column and the first column of the next line combined in one value. Then, everything after that has been shifted from the value you're looking at.

Personally, I'd probably read line by line and then split up each line separately. That way you completely avoid this problem.

By the way, it's much easier for people to read your code if you indent it correctly - you should get into the habit of doing that.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!