» » Java Program to count number of vowels in a string


Solution #1:

  1. package com.javatutorial;
  2.  
  3. public class CountNumberofVowels {
  4.  
  5.  public static void main(String[] args) {
  6.   
  7. System.out.println("Please enter a String");
  8. Scanner in = new Scanner(System.in);                  
  9.  String input = in.nextLine();
  10.  
  11.      char[] Chararray = input.toCharArray();
  12.  
  13.  int count = 0;
  14.  
  15.  for (char ch : Chararray) {
  16.       switch (ch) {
  17.              case 'a':
  18.              case 'e':
  19.              case 'i':
  20.              case 'o':
  21.              case 'u':
  22.              case 'A':
  23.              case 'E':
  24.              case 'I':
  25.              case 'O':
  26.              case 'U':
  27.                  count++;
  28.      break;
  29.      default:
  30.             
  31.      }
  32.  }
  33.        System.out.println("Number of vowels in String "+count);
  34.  
  35. }

  36. }


Output:

  1. Please enter a String
  2. Instance Of Java
  3. Number of vowels in String 6
     
Solution #2:

  1. package com.javatutorial;
  2.  
  3. public class CountNumberofVowels {
  4.  
  5.  public static void main(String[] args) {
  6.  
  7.  int vowels = 0, digits = 0, blanks = 0; char ch; 

  8. System.out.println("Please enter a String");
  9. Scanner in = new Scanner(System.in);                  
  10. String testString= in.nextLine();
  11.  
  12.  
  13. for(int i = 0; i < testString.length(); i ++)
  14. {
  15.  
  16.   ch = testString.charAt(i);
  17.  
  18.   if(ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' ||   
  19.       ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
  20.           vowels ++;
  21.        else if(Character.isDigit(ch))
  22.           digits ++;
  23.      else if(Character.isWhitespace(ch))
  24.            blanks ++;
  25.   }
  26.  
  27.     System.out.println("Vowels : " + vowels);
  28.     System.out.println("Digits : " + digits);
  29.     System.out.println("Blanks : " + blanks);           
  30.    
  31.  
  32. }

  33. }
Output:

  1. Please enter a String
  2. vowels and consonants
  3. Vowels : 6
  4. Digits : 0
  5. Blanks : 2

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu