Need to write a method signature for a method called wordCount() that takes a String parameter, and returns the number of words in that String. For the purposes of this question, a ‘word’ is any sequence of characters; it does not have to be a real English word. Words are separated by spaces. For example: wordCount(“Java”) should return the value 1.
I have written a code, but the problem is in throwing exceptions. I have an error saying: "a string containing must not end with a space in java" and "a string containing must not start with a space in java" my try:
int wordCount(String s){
if (s==null) throw new NullPointerException ("string must not be null");
int counter=0;
for(int i=0; i<=s.length()-1; i++){
if(Character.isLetter(s.charAt(i))){
counter++;
for(;i<=s.length()-1;i++){
if(s.charAt(i)==' '){
counter++;
}
}
}
}
return counter;
}
i<=s.length()-1is normally writteni<s.length(). Also, on what line does the exception occur?