Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Find the most frequent vowel and consonant in a String?
- public class MostFrequentInSentence {
- /**
- * Program: MostFrequentInSentence.java
- * Purpose: Yahoo! Answers
- * Creator: Chris Clarke
- * Created: 26.05.2018
- */
- public static void main (String[] args) {
- int[] freq = new int[26]; // array holds frequency of each letter
- int vowels = 0; // maximum frequency of each vowel
- int consonants = 0; // maximum frequency of each consonant
- char maxV = ' '; // vowel character appearing most often in sentence
- char maxC = ' '; // consonant character appearing most often in sentence
- char ch; // current character in sentence
- int chNum = 0; // number 0-25 of current character in sentence
- String sentence = "How razorback-jumping frogs can level six piqued gymnasts";
- System.out.println ("The sentence is: \"" + sentence + "\"");
- String line = sentence.toLowerCase();
- for (int i = 0; i < line.length(); ++i) {
- ch = line.charAt(i);
- if (ch < 'a' || ch > 'z') continue; // if not a letter, start next loop
- chNum = (int) (ch-'a'); // 0-25
- freq[chNum]++; // increment frequency for this letter
- if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
- if (freq[chNum] > vowels) {
- vowels = freq[chNum];
- maxV = ch;
- }
- } else {
- if (freq[chNum] > consonants) {
- consonants = freq[chNum];
- maxC = ch;
- }
- }
- }
- System.out.println("Vowel that appears most: " + maxV);
- System.out.println("Consonant that appears most: " + maxC);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement