-
Notifications
You must be signed in to change notification settings - Fork 375
Expand file tree
/
Copy pathWordCounter.java
More file actions
33 lines (26 loc) · 906 Bytes
/
WordCounter.java
File metadata and controls
33 lines (26 loc) · 906 Bytes
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
package com.serenitydojo.exceptions;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Paths;
public class WordCounter {
public int numberOfWordsIn(String value){
if(value==null){
return 0;
}
return value.split("\\W").length;
}
public int numberOfWordsInAfile(String fileName) throws IOException {
try {
String fileContents = Files.readString(Paths.get(fileName));
int wordCount = numberOfWordsIn(fileContents);
if(wordCount==0){
throw new FileHasNoWordException("no words found in a file " + fileName);
}
return wordCount;
}
catch(NoSuchFileException noSuchFile){
throw new FileHasNoWordException("no words found in a non existing file " + fileName);
}
}
}