Write a static method named textCount that takes a Scanner representing a file a
ID: 657661 • Letter: W
Question
Write a static method named textCount that takes a Scanner representing a file as a parameter and that reports various statistics about the file. In particular, your method should report the number of lines in the file, the total number of characters (not counting any new-line characters) in the file, and the length and text of the longest line. You may assume that the input file has at least one line of input.
For example, if the file contains the following text:
Twas brillig and the slithy toves
did gyre and gimble in the wabe.
All mimsey were the borogroves,
and the mome raths outgrabe.
"Beware the Jabberwock, my son,
the jaws that bite, the claws that catch,
Beware the JubJub bird and shun
the frumious bandersnatch."
The program would find that there are 9 lines (blank lines count), a total of 254 characters in the file (33 on the first line, 32 on the next line, 31 on the next line, 28 on the next, 0 on the next, etc) and that the longest line is the one that begins with "the jaws that bite". The method would produce the following output:
Total lines = 9
Total chars = 254
Length of longest line = 41
Longest line = the jaws that bite, the claws that catch,
Explanation / Answer
import sun.security.util.Length; import java.io.File; import java.io.FileNotFoundException; import java.util.*; /** * Satisfies the requirements for Question #2 * of Fall CS210 final. * * @author Pat Kaehuaea * 12/6/12 * 7:17 PM */ public class Question2 { public static void main(String[] Args) throws FileNotFoundException{ Scanner inputFile = new Scanner(new File("src/question2.txt")); textCount(inputFile); } /** * Method reads a file line by line, in order to determine * the total number of lines, the length of the longest line, * and which line is longest. The method prints these values * to console as output. * * @param input Scanner object holding file handle for input */ public static void textCount(Scanner input){ //initialize place holder values int numLines = 0; int lengthLongestLine = 0; String longestLine = ""; //process line by line while(input.hasNextLine()){ //assert file has at least one line //increment numLines numLines++; //read each line into String String line = input.nextLine(); //determine if this line is greater than lengthLongestLine if(line.length() > longestLine.length()){ //set lengthLongestLine and longestLine lengthLongestLine = line.length(); longestLine = line; } } //print statistics System.out.println("Total lines = " + numLines); System.out.println("Length of longest line = " + lengthLongestLine); System.out.println("Longest line = " + longestLine); } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.