I need to count the words in a String. For many of you that seems pretty simple but from what I've read in similar questions people are saying to use arrays but I'd rather not. It complicates my program more than it helps as my string is coming from an input file and the program cannot be hardwired to a specific file.
I have this so far:
while(input.hasNext())
{
String sentences = input.nextLine();
int countWords;
char c = " ";
for (countWords = 0; countWords < sentences.length(); countWords++)
{
if (input.hasNext(c))
countWords++;
}
System.out.println(sentences);
System.out.println(countWords);
}
The problem is that what I have here ends up counting the amount of characters in the string. I thought it would count char c as a delimiter. I've also tried using String c instead with input.hasNext but the compiler tells me:
Program04.java:39: incompatible types
found : java.lang.String[]
required: java.lang.String
String token = sentences.split(delim);
I've since deleted the .split method from the program. How do I delimit (is that the right word?) without using a String array with a scanned in file?