String inputString = "Hello! Welcome to Kenzie. My name is Robert, and I'm here with my friend Waldo. Have you met waldo?";
public static int countWords (String inputString){
String[] wordArray = inputString.split(" ");
int count = 0;
for(int j = 0; j < inputString.length(); j++){
if (wordArray[j].equals(" ")) {
// this is supposed to add nothing to count if wordArray[j] is a space
count = count;
}else{
count++;
}
}
return count;
}
When I try running the code I get the error ArrayIndexoutofBoundsException: index 21 out of bounds for the length 21
I’m not sure what I’m doing wrong here.
>Solution :
You can try in this way given below:
public class WordCount {
public static void main(String[] args) {
String inputString = "Hello! Welcome to Kenzie. My name is Robert, and I'm here with my friend Waldo. Have you met waldo?";
String[] arr = inputString.split(" ");
int count = 0;
for (String str : arr) {
if (str != null && !str.trim().equals("")) {
count++;
}
}
System.out.println(count);
}
}
Output:
19