2

Simple program for class to count words and getting the error above and it driving me mad.

int words; //variable to hold word count.

//WordCount methos will count the spaces and punciation.
private int WordCount(string str)
{
    int words = 0; //the number of words counted

    //count the white spaces and punctuation.
    foreach (char ch in str)
    {
        if (char.IsWhiteSpace(ch))
        {
            words++;
        }
        if (char.IsPunctuation(ch))
        {
            words++;
        }

        //return number of words
        return words;
    }
}
1
  • 2
    Move return outside the foreach loop. Commented Nov 13, 2013 at 19:23

3 Answers 3

8

If the string will be empty the return command will not be executed..

Use this instead:

//WordCount methos will count the spaces and punciation.
private int WordCount(string str)
{
    int words = 0; //the number of words counted

    //count the white spaces and punctuation.
    foreach (char ch in str)
    {
        if (char.IsWhiteSpace(ch))
        {
            words++;
        }
        if (char.IsPunctuation(ch))
        {
            words++;
        }
   }

   //return number of words
   return words;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, now having the issue tying to use the returned int of words in an output message box in the button press method. If I declare the int variable before the WordCount method it get stuck with a default value of 0.
3

Your code is returning from inside of foreach loop, if the parameter passed is null, you will get an exception, if it is an empty string, execution will not enter the loop hence the error.

Your current method is also incorrect logically since it will return after first iteration, possibly giving you incorrect result. Your return statement should be outside of foreach loop

Comments

2

Your method is declared as int, which means it MUST return a value. The compiler is complaining that this is not guaranteed to be the case. Specifically if the string is empty your foreach is not entered and no return statement is executed.

On another note, having a forced return on the first iteration makes the foreach pointless.

2 Comments

Thanks, now I have to resolve the not looping as you notes on the return.
I believe the code provided by Tomzan matches what you were trying to do.

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.