Letters A, E, I, O, and U are the vowels.
We would like to write a program that prompts the user to enter a string
Display the number of vowels and consonants in the string.
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Prompt the user to enter a string System.out.print("Enter a string: "); String string = input.nextLine(); int vowels, // Count the number of vowels consonants; // Count the number of consonants vowels = consonants = 0; // Initialize accumulators to 0 // Count the number of vowels and consonants /* ww w. ja v a 2s . c o m*/ //your code here } }
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Prompt the user to enter a string System.out.print("Enter a string: "); String string = input.nextLine(); int vowels, // Count the number of vowels consonants; // Count the number of consonants vowels = consonants = 0; // Initialize accumulators to 0 // Count the number of vowels and consonants for (int i = 0; i < string.length(); i++) { if (Character.isLetter(string.charAt(i))) { if (Character.toUpperCase(string.charAt(i)) == 'A' || Character.toUpperCase(string.charAt(i)) == 'E' || Character.toUpperCase(string.charAt(i)) == 'I' || Character.toUpperCase(string.charAt(i)) == 'O' || Character.toUpperCase(string.charAt(i)) == 'U') { vowels++; } else consonants++; } // Display results System.out.println("The number of vowels is " + vowels); System.out.println("The number of consonants is " + consonants); } } }
The following code uses OR operators.
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a string: "); String entry = input.nextLine().toLowerCase(); int vowelCount = 0; int consonantCount = 0; for (int i = 0; i < entry.length(); i++) { char c = entry.charAt(i); if (isVowel(c)) { vowelCount++; } else if (isConsonant(c)) { consonantCount++; } }//from ww w.j a v a2 s . c om System.out.println("The number of vowels is " + vowelCount); System.out.println("The number of consonants is " + consonantCount); } private static boolean isVowel(char c) { boolean vowel = false; if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { vowel = true; } return vowel; } private static boolean isConsonant(char c) { boolean consonant = false; if (!isVowel(c) && Character.isLetter(c)) { consonant = true; } return consonant; } }