My program counts words and sentences and I figured out how to count words pretty easily but I’m having a problem counting the sentences.
Here’s my code:
Scanner in = new Scanner(file);
in.useDelimiter("");
while (in.hasNext()) {
String word = in.next();
char ch = word.charAt(0);
String temp = readWord.replaceAll("...", " ").replaceAll("--", " ");
if(temp.contains(".") || (temp.contains("!") || temp.contains("?!"))) {
if(ch == '.')
sentences++;
}
}
It works fine with a sentence like:
“Hi, my name is Blah.”
But it doesn’t for this one:
“I don’t know…maybe he doesn’t like it.”
The word counter works but the sentence counter doesn’t. It counts the ellipsis too even when I told it to replace it with an empty space.
Does anyone know what I did wrong?
The
replaceAll()method first argument is a regular expression (regex), not a literal string to match. In a regex, the dot means “any character”. if you really want to match the dot character you have to use a backslash before the dot (and if you want to enter a backslash in a string literal, you need another backslash before the backslash).The other thing is that
replaceAll()does not change the string itself but returns a new string which contains the replacement.