40 likes | 173 Views
CLASS EXERCISE. Demonstrate processing until EOF Write a program that processes an input file ( story.txt ). It must display the number of vowels in each record. The program must also display final vowel totals after all the lines (i.e. records) have been processed.
E N D
CLASS EXERCISE • Demonstrate processing until EOF Write a program that processes an input file (story.txt). It must display the number of vowels in each record. The program must also display final vowel totals after all the lines (i.e. records) have been processed.
CLASS EXERCISE (SOLUTION) import java.io.*; public class CountVowels { public static void main (String[]args) throws IOException { int cntA, cntE, cntI, cntO, cntU; int totA = 0, totE = 0, totI = 0; int totO = 0, totU = 0; char letter; String sentence = null; String fileName = "story.txt"; // declaring input file BufferedReader wordFile = null;
//open input file wordFile = new BufferedReader (new FileReader(inputFileName) ); //priming read sentence = wordFile.readLine(); while (sentence != null) { cntA = 0, cntE = 0, cntI = 0; cntO = 0, cntU = 0; for (int i = 0; i < sentence.length(); i++) { letter = sentence.charAt(i); switch (letter) { case ‘a’: case ‘A’: cntA++; break; case ‘e’: case ‘E’: cntE++; break; case ‘i’: case ‘I’: cntI++; break;
case ‘o’: case ‘O’: cntO++; break; case ‘u’: case ‘U’: cntU++; break; } // end of SWITCH } // end of FOR totA += cntA; totE += cntE; totI += cntI; totO += cntO; totU += cntU; sentence = wordFile.readLine(); //read next } // end of WHILE wordFile.close(); // close file } // end of MAIN