Reputation: 99
SOLVED.
I am trying to count how many punctuation marks there are in a text file. I'm using if statements to count the number of each punctuation mark and doesn't seem to be working, it says every element is a full stop.
this is my loop
for (int c = 0; c <= punk1.size()-1; c++) {
if (punk1.get(c).matches(".")) {
fullstop += 1;
} else if (punk1.get(c).matches(",")) {
comma += 1;
} else if (punk1.get(c).matches("?")) {
qmark += 1;
} else if (punk1.get(c).matches("!")) {
expoint += 1;
} else if (punk1.get(c).matches("\"")) {
doublequote += 1;
} else if (punk1.get(c).matches("\'")){
singlequote += 1;
} else {
System.out.println("Punctuation Marks not Found");
}
}
and this is the output.
Punctuation marks in text file: [., ., ., ,, ,, ,, !, !, !, ?, ?, ?, ", ",", ', ', ']
Number of Punctuation marks in file: 18
Number of fullstops: 18
Number of commass: 0
Number of question marks: 0
Number of exclamation point: 0
Number of double quotes: 0
Number of singlequotes: 0
there should be 3 for each.
Upvotes: 1
Views: 1195
Reputation: 1599
When you use matches keyword with the regex expression, you should be careful with the regex expression.
You have to escape .
?
"
and '
with backslash.
Try the following code:
for (int c = 0; c <= punk1.size()-1; c++) {
if (punk1.get(c).matches("\\.")) {
fullstop += 1;
} else if (punk1.get(c).matches(",")) {
comma += 1;
} else if (punk1.get(c).matches("\\?")) {
qmark += 1;
} else if (punk1.get(c).matches("!")) {
expoint += 1;
} else if (punk1.get(c).matches("\"")) {
doublequote += 1;
} else if (punk1.get(c).matches("\'")){
singlequote += 1;
} else {
System.out.println("Punctuation Marks not Found");
}
}
Alternatively, You can also use equals
for comparison.
Upvotes: 1
Reputation: 52185
The .matches
method takes a regular expression as parameter. The problem, in your case, is that the period character is a special character in regular expression syntax, which means match any character, thus, your first if
statement will always hold true.
To fix this, you can simply replace punk1.get(c).matches(".")
with punk1.get(c).matches("\\.")
. This will escape the period character so that it will be matched literally.
Alternatively, you can use the contains
method which will take the strings as they are.
Upvotes: 3
Reputation: 5463
You are using matches
which uses a regex match. Since '.' matches any character the first if condition is always true.
Upvotes: 4