Write a method called inputStats that accepts a Scanner repr
Write a method called inputStats that accepts a Scanner representing an input file and reports for each line its line position, the number of tokens in that line, and the length of the longest token in that line. To do this, consider reading each line of the file using the nextLine method, creating a Scanner from the input line, and accessing the tokens in that line using next and hasNext. For example, if the file had lines
Beware the Jabberwock, my son,
the hawas that bite, the claws that catch,
Beware the JubJub bird and shun
the frumious bandersnatch
then the output of the program should be:
Line 1 has 5 tokens (longest = 11)
Line 2 has 8 tokens (longest = 6)
Line 3 has 6 tokens (longest = 6)
Line 4 has 3 tokens (longest = 13)
Solution
InputStatsTest.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class InputStatsTest {
public static void main(String[] args) throws FileNotFoundException {
File file = new File(\"input.txt\");
if(file.exists()){
Scanner scan = new Scanner(file);
inputStats(scan);
}
else{
System.out.println(\"File does not exist\");
}
}
public static void inputStats(Scanner scan){
String line=\"\";
int max = 0;
int count = 0;
while(scan.hasNextLine()){
max= 0;
line = scan.nextLine();
count++;
String tokens[] = line.split(\" \");
for(int i=0; i<tokens.length; i++){
if(max < tokens[i].length()){
max = tokens[i].length();
}
}
System.out.println(\"Line \"+count+\" has \"+tokens.length+\" tokens (longest = \"+max+\") \");
}
}
}
Output:
Line 1 has 5 tokens (longest = 11)
Line 2 has 8 tokens (longest = 6)
Line 3 has 6 tokens (longest = 6)
Line 4 has 3 tokens (longest = 12)
