Advertisement
Guest User

Untitled

a guest
May 23rd, 2018
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.08 KB | None | 0 0
  1. import edu.duke.*;
  2.  
  3. public class WordLengths {
  4.  
  5.     public void countWordLengths(FileResource fr, int[] counts) {
  6.         for (String s : fr.words()) {
  7.             int wadu = s.length();
  8.             for (int k = 0; k < wadu; k++) {
  9.                 if (Character.isLetter(s.charAt(k)) == false) {
  10.                     wadu--;
  11.                 }
  12.             }
  13.             if (wadu >= 30) {
  14.                 counts[30]++;
  15.             } else {
  16.                 counts[wadu]++;
  17.             }          
  18.         }
  19.         for (int i = 0; i < 31; i++) {
  20.             if (counts[i] != 0) {
  21.                 System.out.println("Words with length " + i + " : " + counts[i]);
  22.             }
  23.         }
  24.         int max[] = counts;
  25.         System.out.println("Most number of words for one length: " + indexOfMax(max));
  26.     }
  27.    
  28.     public void testCountWordLengths() {
  29.         FileResource fr = new FileResource("smallHamlet.txt");
  30.         int[] counts = new int[31];
  31.         countWordLengths(fr, counts);
  32.     }
  33.    
  34.     public int indexOfMax(int[] values) {
  35.         int max = 0;
  36.         for (int i = 0; i < 31; i++) {
  37.             if (values[i] >= max) {
  38.                 values[i] = max;
  39.             }
  40.         }
  41.         return max;
  42.     }
  43.    
  44.     public static void main(String[] args) {
  45.         WordLengths run = new WordLengths();
  46.         run.testCountWordLengths();
  47.     }
  48.    
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement