简单的类(class)程序来计算单词并出现上述错误,这让我抓狂。
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;
}
}
最佳答案
如果字符串为空,返回命令将不会被执行..
改用这个:
//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;
}
关于C#并非所有代码路径都在简单方法中返回值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19962513/