0

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;
    } 
3
  • i<=s.length()-1 is normally written i<s.length(). Also, on what line does the exception occur? Commented Nov 1, 2013 at 1:00
  • @JohnGaughan - The point is the exception doesn't occur, but needs to. Commented Nov 1, 2013 at 11:40
  • @Hot Licks - ah, I get that now rereading the question more slowly. At first it sounded like he was getting those exceptions, but they are unlike any built-in exception I have seen so I should have known. Commented Nov 5, 2013 at 21:46

4 Answers 4

1

You're on the right track with your exception handling, but not quite there (as you've noticed).

Try the code below:

public int wordCount(final String sentence) {
    // If sentence is null, throw IllegalArgumentException.
    if(sentence == null) {
        throw new IllegalArgumentException("Sentence cannot be null.");
    }
    // If sentence is empty, throw IllegalArgumentException.
    if(sentence.equals("")) {
        throw new IllegalArgumentException("Sentence cannot be empty.");
    }
    // If sentence ends with a space, throw IllegalArgumentException. "$" matches the end of a String in regex.
    if(sentence.matches(".* $")) {
        throw new IllegalArgumentException("Sentence cannot end with a space.");
    }
    // If sentence starts with a space, throw IllegalArgumentException. "^" matches the start of a String in regex.
    if(sentence.matches("^ .*")) {
        throw new IllegalArgumentException("Sentence cannot start with a space.");
    }

    int wordCount = 0;

    // Do wordcount operation...

    return wordCount;
}

Regular Expressions (or "regex" to the cool kids in the know) are fantastic tools for String validation and searching. The method above practices fail-fast implementation, that is that the method will fail before performing expensive processing tasks that will just fail anyway.

I'd suggest brushing up on both practices covered here, bot regex and exception handling. Some excellent resources to help you get started are included below:

Sign up to request clarification or add additional context in comments.

3 Comments

Rather than matches I'd simply use charAt(0) and charAt(sentence.length() - 1), compared to blank.
@HotLicks Yeah, that works too. I usually use regex for validation as it's concise, tidy and easy to read (providing you're familiar with regex).
I'm familiar with regex but I always have to scratch my head for several minutes (and likely consult a reference) to figure one out. charAt is far more straightforward. But either approach is far better than mucking with split (which I suppose can be made to work, but only with difficulty).
0

I would use the String.split() method. This takes a regular expression which returns a string array containing the substrings. It is easy enough from there to get and return the length of the array.

This sounds like homework so I will leave the specific regular expression to you: but it should be very short, perhaps even one character long.

Comments

0

I would use String.split() to handle this scenario. It will be more efficient than the pasted code. Make sure you check for empty characters. This will help with sentences with multiple spaces (e.g. "This_sentences_has__two_spaces).

 public int wordCount(final String sentence) {
    int wordCount = 0;
    String trimmedSentence = sentence.trim();
    String[] words = trimmedSentence.split(" ");
    for (int i = 0; i < words.length; i++) {
        if (words[i] != null && !words[i].equals("")) {
            wordCount++;
        }
    }
    return wordCount;
}

Comments

0

I would use the splitter from google guava library. It will work more correctry, because standart String.split() working incorrectly even in this simple case:

// there is only two words, but between 'a' and 'b' are two spaces
System.out.println("a  b".split(" ").length);// print '3' becouse but it think than there is 
// empty line between these two spaces

With guava you can do just this:

Iterables.size(Splitter.on(" ").trimResults().omitEmptyStrings().split("same  two_spaces"));// 2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.