Objectives To gain experience with string objects To gain ex
Solution
import java.io.*;
public class wordCount {
public static void main(String args[]) {
File f = new File(\"e:\\\\cs1.txt\");
if(f.exists()){
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String line = \"\", str = \"\";
int a = 0;
int b = 0;
while ((line = br.readLine()) != null) {
str += line + \" \";
b++;
}
System.out.println(\"Total \" + b + \" lines in a file\");
System.out.println(str);
StringTokenizer st = new StringTokenizer(str);
while (st.hasMoreTokens()) {
String s = st.nextToken();
a++;
}
System.out.println(\"Total \" + a + \" words are in the file\");
System.out.println(\"Total punctuations are in the file\");
String s = str.next();
countPunctuation(s);
for(int i = 0; i < str.length(); i ++)
{
ch = str.charAt(i);
if(ch == \'a\' || ch == \'A\' || ch == \'e\' || ch == \'E\' || ch == \'i\' ||
ch == \'I\' || ch == \'o\' || ch == \'O\' || ch == \'u\' || ch == \'U\')
vowels ++;
else if(Character.isDigit(ch))
digits ++;
else if(Character.isWhitespace(ch))
blanks ++;
}
System.out.println(\"Vowels : \" + vowels);
System.out.println(\"Digits : \" + digits);
System.out.println(\"Blanks : \" + blanks);
}else{
System.out.println(\"File not found!\");
}
}
public static int countPunctuation(String s)
{
int periodCount = 0;
int commaCount = 0;
int semicolonCount = 0;
int colonCount = 0;
int exclamationCount = 0;
int questionCount = 0;
int total = 0;
for(int i = 0; i < s.length(); i++)
{
if(s.charAt(i) = \".\")
{
periodCount++;
total++;
}
if(s.charAt(i) = \",\")
{
commaCount++;
total++;
}
if(s.charAt(i) = \";\")
{
semicolonCount++;
total++;
}
if(s.charAt(i) = \":\")
{
colonCount++;
total++;
}
if(s.charAt(i) = \"!\")
{
exclamationCount++;
total++;1
}
if(s.charAt(i) = \"?\")
{
questionCount++;
total++;
}
}
System.out.println(\"There are \" + periodCount + \" periods in this String.\");
System.out.println(\"There are \" + commaCount + \" commas in this String.\");
System.out.println(\"There are \" + semicolonCount + \" semicolons in this String.\");
System.out.println(\"There are \" + colonCount + \" colons in this String.\");
System.out.println(\"There are \" + exclamationCount + \" exclamation marks in this String.\");
System.out.println(\"There are \" + questionCount + \" quesiton marks in this String.\");
return total;
}
}


