I am trying to get into java and i am stuck on a problem which is to count only words in a java file using a scanner
while (sc.hasNextLine()) {
sc.next();
count++; }
and this is the answer to most of the questions i have seen although this counts everything including numbers punctuation etc.
So what is the best approach to check for words only ?
You could keep your original code, and them match it with (allows apostrophes but doesn't allow apostrophes at the start)
if (word.matches("[a-zA-Z']+") && !word.matches("'")) {
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.