I trying to make a word count program without having to use split(). Okay, before you guys tell me off saying this is a duplicate. I know. the other solution wasn't very specific to me as they were using the add method.
public static void findWord()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a sentence");
String sentence = input.nextLine();
int numOfWords = count(sentence);
here count comes up as an error.
System.out.println("input: " + sentence);
System.out.println("number of words: " + numOfWords);
}
As Stefan mentioned, you are missing a count
method (as that is what you trying to call when you say count(sentence);
)
Slightly different answer here as you asked not to use split()
public static int count(String s) {
int count = 1; //to include the first word
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') {
count++;
}
}
return count;
}
A better way to do it, if spaces is an issue is:
StringTokenizer st = new StringTokenizer(sentence);
System.out.println(st.countTokens());