Looking at posts like "How do i return the last generated number in a for loop?", "How do I return a value from within a for loop?", and "Having trouble returning a value outside of a for loop with Java" did not help because the problems described in the posts seem tangent to the post titles.
I am receiving the error: "error: missing return statement".
I am trying to create a word count by first setting the word count to 1. The for loop is to traverse a String sentence. Each time a space is found in the String, word count will increase by 1.
Where do I put a return statement so that the program works as intended? I can't put a return statement on the outside of the loop because then 1, the initial value of wc, will be returned.
// wc = word count
public static int wordCount(String sentence) {
int wc = 1;
for (int a = 0; a <= sentence.length()-1; a++) {
if (sentence.charAt(a) == ' ') {
wc += 1;
}
if (a == sentence.length()-1) {
return wc;
}
}
}