I should first of all say this is an assignment that is confusing me, I've already corrected one of the questions by the lecturer :/
Anyway, I've made a method which counts the words using booleans, a while loop and a counter.
However I need to some how shape this into a recursive method that counts the amount of words in a string, a word is delimited by one or many spaces.
countWords(" hello this is an example", 0); // returns 5
As you can see the only parameters are countWords(String s, int i) making it more difficult.
Also, within the method I'm restricted to only using these three methods s.charAt(0), s.substring(1) and s.equals("") again making it more of a head hurter :)
This is the none recursive method I wrote using a while loop:
public static int countWords(String s) {
int words = 0;
boolean spaceBefore = true;
boolean spaceCurrently = false;
while(true) {
if (s.equals(""))
return words;
if (s.charAt(0) == ' ')
spaceCurrently = true;
else
spaceCurrently = false;
if (spaceBefore && !spaceCurrently)
words++;
spaceBefore = spaceCurrently;
s = s.substring(1);
}
}