计数单词功能没有给出正确的答案

时间:2014-09-12 02:21:55

标签: java

我正在编写一个Count Words函数,但每次只有一个字母时,它不会计算句子中的第一个单词。最小和最大输入是单词的最大字符和最小字符。任何帮助或建议都会很棒。

public static int countWords (String word, int min, int max)
{
    int WordCount = 0;
    int CharacterCount = 0;
    int StringLength = word.length();
    int n = 0;

    while (StringLength > 0)
    {
        if (Character.isLetter(word.charAt(n)))
        {
            CharacterCount = CharacterCount + 1;
        }
        else
        {
            if (CharacterCount >= min && CharacterCount <= max)
            {
                WordCount = WordCount + 1;
            }
            else
            {
                WordCount = WordCount;
            }
        CharacterCount = 0; 
        }
    n = n + 1;  
    StringLength = StringLength - 1;
    }
return WordCount;   
}

2 个答案:

答案 0 :(得分:0)

如果输入只是一个字符并且实际上是一个字母,那么您将只输入第一个if语句,将CharacterCount设置为1。

WordCount仍将保持为0

else是否必要?

答案 1 :(得分:0)

删除不必要的else块,并在while循环结束时添加另一个if。问题是最后的单词没有正确计算。

public class WordCount {

    public static int countWords (String word, int min, int max)
    {
        int WordCount = 0;
        int CharacterCount = 0;
        int StringLength = word.length();
        int n = 0;

        while (StringLength > 0)
        {
            if (Character.isLetter(word.charAt(n)))
            {
                CharacterCount = CharacterCount + 1;
            }
            else
            {
                if (CharacterCount >= min && CharacterCount <= max)
                {
                    WordCount = WordCount + 1;   
                }
                CharacterCount = 0;
            }
            n = n + 1;  
            StringLength = StringLength - 1;
        }
        if ( CharacterCount > 0 ) {
            WordCount++;
        }

        return WordCount;   
    }

    public static void main(String[] args) {
        System.out.println( countWords("a b c", 1, 1) );
        System.out.println( countWords("This is a string", 1, 100) );
    }
}