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:
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
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.
subject: How to count and scan the number of characters in a line?