1+ /*********************************************************************************
2+ * (Count consonants and vowels) Write a program that prompts the user to enter a *
3+ * text file name and displays the number of vowels and consonants in the file. *
4+ * Use a set to store the vowels A, E, I, O, and U. *
5+ *********************************************************************************/
6+ import java .util .*;
7+ import java .io .*;
8+
9+ public class Exercise_21_04 {
10+ public static void main (String []args )throws Exception {
11+ // Create a Scanner
12+ Scanner input =new Scanner (System .in );
13+
14+ // Prompt the user to enter a text file name
15+ System .out .print ("Enter a text file name: " );
16+ String fileName =input .next ();
17+
18+ // Check if file exists
19+ File file =new File (fileName );
20+ if (!file .exists ()) {
21+ System .out .println ("The file " +fileName +" does not exist." );
22+ System .exit (1 );
23+ }
24+
25+ // Create a set to store vowels
26+ Set <Character >set =new HashSet (Arrays .asList ('A' ,'E' ,'I' ,'O' ,'U' ));
27+ int vowels =0 ;// Counts the number of vowels
28+ int consonants =0 ;// Counts the number of consonants
29+
30+ // Count the number of vowels and consonants in the file
31+ try (// Create an input file
32+ Scanner inputFile =new Scanner (file );
33+ ) {
34+ while (inputFile .hasNext ()) {
35+ String line =inputFile .nextLine ();
36+ for (int i =0 ;i <line .length ();i ++) {
37+ if (set .contains (Character .toUpperCase (line .charAt (i ))))
38+ vowels ++;
39+ else if (Character .isLetter (line .charAt (i )))
40+ consonants ++;
41+ }
42+ }
43+ }
44+
45+ // Display the number of vowels and consonants in the file
46+ System .out .println ("The file " +fileName +" has " +vowels +
47+ " vowels and " +consonants +" consonants." );
48+ }
49+ }