Respuesta :

Answer:

The java program is as follows.

import java.util.Scanner;

import java.lang.*;

public class Main

{

   // string array to hold vowels

   static String[] vowels = {"A", "E", "I", "O", "U"};

   

   // variables declared

   static String word;

   static int vowel_count = 0;

   static int consonant_count = 0;

   static String ch;

   static int len;

   

   public static void main(String[] args) {

   

   Scanner sc = new Scanner(System.in);

   

   // user asked to enter a string

   System.out.print("Enter any string consisting of vowels and consonants: ");

   word = sc.nextLine();

   

   // length of string stored in a variable

   len = word.length();

   

   // enhanced for loop used

   for(String v : vowels)

   {

   for(int n=0; n<len; n++)

   {

       // each character in user entered string is tested

       ch = word.substring(n,n+1);

       

       if(ch.equalsIgnoreCase(v))

           vowel_count = vowel_count + 1;

   }

   }

   

   // length of word minus number of vowels give the consonant count

   consonant_count = len - vowel_count;

   

   // number of vowels and consonants displayed

   System.out.println("The string " + word + " has " + vowel_count + " vowels and " + consonant_count + " consonants.");

   

 }

}

OUTPUT

Enter any string consisting of vowels and consonants: TESTING

The string TESTING has 2 vowels and 5 consonants.

Explanation:

1. The program has string variables to enable the usage of string functions.

2. The integer variables are declared to hold the count of vowels, the count of consonants and the length of the user entered string.

3. A string array is declared and initialized with vowels.

4. The string functions are used to compute length of the string, substring yields each character in the user inputted string.

5. Each character in the input string is compared with each of the vowels.

6. Outer enhanced for loop executes on the array holding vowels. Inner for loop executes for each character in the user input string and compares each character with each vowel from the outer enhanced for loop.

7. The program works irrespective of the case of the characters both in the array and in the user entered string.

ACCESS MORE