JAVA: token-based file input write a java application that reads a text file and
ID: 3759208 • Letter: J
Question
JAVA: token-based file input
write a java application that reads a text file and then displays the follow statistics about the file's content:
1. total number of words
2. total number of non-words (token containing any non-letter)
3. total number of words with length 4 or less
4. total number of words with length between 5 and 8, inclusive
5. total number of words with length greater than or equal to 9
6. total number of words containing the word "life"
*must read the file one token at a time. Can only use String class methods length, indexOf and charAt as well as Scanner class methods next and hasNext.
Explanation / Answer
import java.util.*;
import java.io.*;
public class TextFileInfoPrinter
{
public static void main(String[]args) throws FileNotFoundException
{
Scanner console = new Scanner(System.in);
System.out.println("File to be read: ");
String inputFile = console.next();
File file = new File(inputFile);
Scanner in = new Scanner(file);
int words = 0;
int lines = 0;
int chars = 0;
int c=0;
while(in.hasNextLine()) {
lines++;
String line = in.nextLine();
for(int i=0;i<line.length();i++)
{
if(line.charAt(i)!=' ' && line.charAt(i)!=' ')
chars ++;
}
words += new StringTokenizer(line, " ,").countTokens();
}
for(int i=0;i<s.length()-str.length();
i++)
{
if((s.charAt(i-1)==' ')&&(s.charAt(i+str.length()+1)==' ')
{
// to check that is it a new wor ut has spaces around it
if(s.substring(i,i+str.length()).equalsIgnoreCase(str))
{
life++;
}
}
}
System.out.println("Number of lines: " + lines);
System.out.println("Number of words: " + words);
System.out.println("Number of characters: " + chars);
System.out.println("Number of string containing life:" + life);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.