Advertisement
brilliant_moves

MostFrequentInSentence.java

May 26th, 2018
291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.56 KB | None | 0 0
  1. //  Find the most frequent vowel and consonant in a String?
  2.  
  3. public class MostFrequentInSentence {
  4.  
  5.     /**
  6.       * Program: MostFrequentInSentence.java
  7.       * Purpose: Yahoo! Answers
  8.       * Creator: Chris Clarke
  9.       * Created: 26.05.2018
  10.       */
  11.  
  12.     public static void main (String[] args) {
  13.  
  14.         int[] freq = new int[26];   // array holds frequency of each letter
  15.         int vowels     =   0;   // maximum frequency of each vowel
  16.         int consonants =   0;   // maximum frequency of each consonant
  17.         char maxV      = ' ';   // vowel character appearing most often in sentence
  18.         char maxC      = ' ';   // consonant character appearing most often in sentence
  19.         char ch;        // current character in sentence
  20.         int chNum      =   0;   // number 0-25 of current character in sentence
  21.  
  22.         String sentence = "How razorback-jumping frogs can level six piqued gymnasts";
  23.         System.out.println ("The sentence is: \"" + sentence + "\"");
  24.         String line = sentence.toLowerCase();
  25.         for (int i = 0; i < line.length(); ++i) {
  26.             ch = line.charAt(i);
  27.             if (ch < 'a' || ch > 'z') continue; // if not a letter, start next loop
  28.             chNum = (int) (ch-'a');     // 0-25
  29.             freq[chNum]++;          // increment frequency for this letter
  30.             if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
  31.                 if (freq[chNum] > vowels) {
  32.                     vowels = freq[chNum];
  33.                     maxV = ch;
  34.                 }
  35.             } else {
  36.                 if (freq[chNum] > consonants) {
  37.                     consonants = freq[chNum];
  38.                     maxC = ch;
  39.                 }
  40.             }
  41.         }
  42.         System.out.println("Vowel that appears most: " + maxV);
  43.         System.out.println("Consonant that appears most: " + maxC);
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement