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;
}
}
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;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With