Reputation: 35
I'm trying to get a word count of a string entered by a user but I keep getting "0" back as a result. I can't figure out what to do.
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner reader=new Scanner(System.in);
ArrayList<String> A=new ArrayList<String>();
System.out.print("Enter a sentence: ");
String a=reader.next();
int charCount=a.length();
int space;
int period;
int wordCount=0;
//word count\
for (int i=0; i<1; i++){
space=a.indexOf(" ");
if (a.charAt(0)!=' '){
if (space!=-1){
A.add(i, a.substring(0, space-1));
a=a.substring(a.indexOf(" ")+1, charCount-1);
}
if (space==-1&&a.charAt(charCount-1)=='.'){
period=a.indexOf(".");
A.add(i, a.substring(0, period));
}
charCount=a.length();
}
wordCount=A.size();
}
System.out.print("Word Count: "+A.size());
}
Upvotes: 1
Views: 80
Reputation: 904
Why don't you try like this-
public static void main (String[] args) {
Scanner reader=new Scanner(System.in);
System.out.println("Enter a sentence: ");
String str1 = reader.nextLine();
String[] wordArray = str1.trim().split("\\s+");
int wordCount = wordArray.length;
System.out.println("Word count is = " + wordCount);
}
Upvotes: 1