Friday 19 August 2016

Chapter 5 Exercise 49, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*5.49 (Count vowels and consonants) Assume letters A, E, I, O, and U as the vowels. Write a program that prompts the user to enter a string and displays the number of vowels and consonants in the string.


Enter a string: Programming is fun
The number of vowels is 5
The number of consonants is 11

import java.util.Scanner;
 
public class ProgrammingEx5_49 {
 
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  System.out.print("Enter a string:");
  String s = input.nextLine();
  String s2 = "";
  int numberOfVowel = 0;
  int numberOfCon = 0;
 
  for (int i = s.length() - 1; i >= 0; i--) {
   switch (s.toLowerCase().charAt(i)) {
   case 'a':
   case 'e':
   case 'i':
   case 'o':
   case 'u':
    numberOfVowel++;
    break;
   case ' ':
    break;
   default:
    numberOfCon++;
    break;
 
   }
  }
 
  System.out.println("The number of vowels is " + numberOfVowel);
  System.out.println("The number of consonants is " + numberOfCon);
 
 }
 
}

No comments :

Post a Comment