Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I'm trying to make a method that counts the total number of words in an array without the spaces

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading