Search code examples
javadrjava

Please help me finish my DrJava code. I'm confused on how to finish it


Design and implement an application that reads a string from the user, then determines and prints the number of vowels and consonants which appear in the string. Use a switch statement inside a loop.

A typical program output might be:

Enter a sentence
> My dog has fleas!
Sentence is : My dog has fleas!
VowelVount is : 4
ConsonantCount is : 9

My code is:

import java.util.Scanner;

public class VnC{

  public static void main(String [] args){
    String text;
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter a sentence");
    text = scan.nextLine();
    System.out.println("Sentence is : " + text);
    text = text.toLowerCase();
    switch(text) {
      case 'a':
      case 'e':
      case 'i':
      case 'o':
      case 'u':
        vowelCount++;
        System.out.println("VowelCount : " + vowelCount);
        break;
      default:
        consonanyCount++;
        System.out.println("ConsonantCount is : " + consonantCount);
        break;
    }
  }

}

Solution

  • for (char ch : text.toCharArray()) { 
      switch(ch) {
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u':
          vowelCount++;
          break;
        default:
          consonanyCount++;
          break;
      }
    } 
    System.out.println("VowelCount : " + vowelCount);
    System.out.println("ConsonantCount is : " + consonantCount);