-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWordLengths.java
75 lines (64 loc) · 2.39 KB
/
WordLengths.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import java.io.*;
public class WordLengths {
/* Count word length */
public static void countWordLengths(String message, int[] counts) {
/* Split words to word */
String[] words = message.split(" ");
// for String word and word not empty
for (String word : words) {
if (!word.isEmpty()) {
int wordLength = word.length();
if (!Character.isLetter(word.charAt(wordLength - 1))) {
wordLength--;
}
if (!Character.isLetter(word.charAt(0))) {
wordLength--;
}
if (wordLength >= counts.length) {
counts[counts.length - 1]++;
} else if (wordLength > 0) {
counts[wordLength]++;
}
}
}
}
/* Index of the largest element in values */
public static int indexOfMax(int[] values) {
int maxIndex = 0;
for (int k = 0; k < values.length; k++) {
if (values[k] > values[maxIndex]) {
maxIndex = k;
}
}
return maxIndex;
}
/* Test Count Word Length */
public static void testCountWordLengths() {
try {
/* Read message from file */
File file = new File("C:\\Users\\MitchHuang\\Desktop\\Project\\Duke-univerity\\course3\\CharacterStuff\\CaesarCipher\\romeo.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String message = "";
String line;
while ((line = br.readLine()) != null) {
message += line + "\n";
}
br.close();
System.out.println(message);
int[] counts = new int[31];
countWordLengths(message, counts);
for (int i = 0; i < counts.length; i++) {
if (counts[i] != 0) {
System.out.println(counts[i] + " words of length " + i);
}
}
int maxIndex = indexOfMax(counts);
System.out.println("Most common word length in the file is " + maxIndex);
} catch (IOException e) {
System.out.println("Error reading file");
}
}
public static void main(String[] args) {
testCountWordLengths();
}
}