Objectives To gain experience with string objects To gain ex
Solution
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;
public class wordcount {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println(\"Input the File Name to be processed\");
String file = scanner.nextLine();
File f = new File(file);
if(f.exists() && !f.isDirectory()) {
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
int countLines = 0,countWords = 0,countAlphaNumericChars = 0,countSentences = 0;
String line;
String delimiters = \"?!.\";
while ((line = br.readLine()) != null) {
countLines++;
String[] words = line.replaceAll(\"\\\\s+\",\" \").split(\" \");
countWords += words.length;
for (int i = 0; i < line.length(); i++) {
if (delimiters.indexOf(line.charAt(i)) != -1) { // If the delimiters string contains the character
countSentences++;
}
}
for(String s:words) {
String pattern = \"[a-zA-Z0-9]*\";
String newString = s.replaceAll(pattern, \"\");
countAlphaNumericChars += (s.length()-newString.length());
}
}
System.out.println(\"Total Lines : \"+countLines);
System.out.println(\"Total Words : \"+countWords);
System.out.println(\"Total Alpha Numeric Chars : \"+countAlphaNumericChars);
System.out.println(\"Total Sentences : \"+countSentences);
}
catch (Exception e) {
e.printStackTrace();
}
}
else {
System.out.println(\"File Not present in this directory\");
}
}
}

