I am new to java, and have this assignment do when I have to count consonants and vowels among other thigs , and I already wrote a program that works. However, I feel that there is still room for improvement specifically in the vowel and consonant counts. Could you help me out here?

import java.util.Scanner;

public class Phrase
{
   public static void main (String[] args) throws Exception
   {
      Scanner input = new Scanner (System.in);
      String comment; 
      String comment2;
      int vowel =0, con =0;
      
      System.out.println("Enter a phrase, sentence or paragraph.");
      comment = input.nextLine();
      
      comment2 = comment.toUpperCase();
      System.out.println("All up-cased: \n" + comment2);
      
      comment2 = comment.toLowerCase();
      System.out.println("All down-cased: \n" + comment2);
      
      char[] count = comment2.toCharArray();
      for (int i = 0; i < comment2.length(); i++)
      {
         if(count[i] == 'a' ||  count[i] == 'e' || 
            count[i] == 'i' || count[i] == 'o' ||
            count[i] == 'u')
         {
            ++vowel;
         }
         else if(count[i] == 'q' || count[i] == 'w' ||
               count[i] == 'r' || count[i] == 't' ||
               count[i] == 'y' || count[i] == 'p' || 
               count[i] == 's' || count[i] == 'd' ||
               count[i] == 'f' || count[i] == 'g' ||
               count[i] == 'h' || count[i] == 'j' || 
               count[i] == 'k' || count[i] == 'l' || 
               count[i] == 'z' || count[i] == 'x' ||
               count[i] == 'c' || count[i] == 'v' || 
               count[i] == 'b' || count[i] == 'n' || 
               count[i] == 'm')
         {
            ++con;
         }
      }
      
      System.out.println("Number of vowels: \n" + vowel);
      System.out.println("Number of consonants: \n" + con);
      
      StringBuffer buffer = new StringBuffer(comment);
      comment2 = buffer.reverse().toString();
      System.out.println("Reverse Order: \n" + comment2);
   }
}
Member Avatar for ztini

You will find excellent code reduction from using switch(int) in this case.

So, something like this:

int vowels = 0, constants = 0;
		for (char c : comment.toCharArray()) {
			switch(c) {
				case 'a':
				case 'e':
				case 'i':
				case 'o':
				case 'u': vowels++; break;
				default: constants++;
			}
		}

Thanks your method works too, and it is much shorter.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.