-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWordCount.java
93 lines (84 loc) · 2.49 KB
/
WordCount.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class WordCount
{
enum State
{
START,
WORD,
DELIM,
}
private static TextInfo analyzeText(String fileName) throws IOException
{
try (BufferedReader reader = new BufferedReader(
new FileReader(fileName)))
{
long charCount = 0;
long wordCount = 0;
long lineCount = 0;
State state = State.START;
int c;
while ((c = reader.read()) != -1)
{
charCount++;
char ch = (char) c;
switch (state)
{
case START:
lineCount++;
if (Character.isLetterOrDigit(ch))
{
state = State.WORD;
wordCount++;
}
else
{
state = State.DELIM;
if (ch == '\n') {lineCount++;}
}
break;
case WORD:
if (!Character.isLetterOrDigit(ch))
{
state = State.DELIM;
if (ch == '\n') {lineCount++;}
}
break;
case DELIM:
if (Character.isLetterOrDigit(ch))
{
state = State.WORD;
wordCount++;
}
else if (ch == '\n')
{
lineCount++;
}
break;
}
}
return new TextInfo(fileName, charCount, wordCount, lineCount);
}
}
public static void main(String[] args)
{
if (args.length < 1)
{
System.err.println("you must specify at least one filename");
}
for (String fileName : args)
{
try
{
TextInfo data = analyzeText(fileName);
System.out.println(data);
}
catch (IOException exception)
{
System.err.printf("%s: unable to process the file\n",
fileName);
}
}
}
}