This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to count and scan the number of characters in a line?

 
Ashley Kin
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I'm trying to use file line/token processing to read the number of lines and characters, and determine the longest line, then print the text of the longest line.

I have the number of lines down, but I'm having trouble with the other three things. Is there a nextChar() method, like the nextInt() one?
It is a static method that takes a Scanner representing a file as a parameter and then reports statistics about the file.

This is the portion of the main method that pertains to the method textCount:


And this is what I have so far:


Thank you for any help!
 
Harsha Smith
Ranch Hand
Posts: 287
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ashley, you've made a good effort to solve the problem. The following code may give you some idea on how to finish it off. There are some errors in your class. Check the method declarations and avoid unnecessary creation of scanner objects etc
 
Campbell Ritchie
Sheriff
Posts: 48424
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the idea was to count the characters by hand. Not an easy task.
There is not, unfortunately, a nextChar() method in Scanner. There is nextByte(), but I don’t think that will solve the problem. You can try adding a newline character (\n) to the end of each line of input and scanning the input line character by character until the newline appears. You can try nextByte(), but that will only give you one byte per letter if you stick to ASCII letters and use an 8-bit encoding eg UTF-8, or (not certain) ISO 8859-1(???).

You could also try the read() method of something like FileReader, which returns an int, until you get to a line terminator character (look here with ctrl-F “Line Terminator”), counting the ints. Beware. If you simply test for (i != '\n'), that will miss the \r character at the end of each line in a Windows® file, so all your lines will be one character too long. But you will still correctly identify the longest line.

The String#length() method is so much simpler to use, and works for all languages except Eastern Asian ones, so anybody would use that.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic