有效字计数器越界错误

时间:2015-01-27 15:56:07

标签: java

{
    public static int WordCount (String cString)
    {       
        String currentWord;
        int index;
        int spacePos;
        int validWordCount=0;
        boolean validWord;
        char upClowC;

        cString=cString.trim()+" ";

        spacePos=cString.indexOf(" ");

        validWord=true;

        for(index=0;index<cString.length();index++)
        {
            currentWord=cString.substring(0,spacePos);
            upClowC=Character.toUpperCase(currentWord.charAt(index));
            if(upClowC<'A'||upClowC>'Z')
            {
                validWord=false;
            }   
        }

        if(validWord==true)
        {
            validWordCount++;
        }

        return validWordCount;
    }

    public static void main(String[] args)
    {
        String sentence;

        System.out.println("enter a sentence:");
        sentence=EasyIn.getString();

    WordCount(sentence);
    }
}

我正在尝试创建一个方法,它接受一个句子并选出有效的单词(即没有数字或符号),但我不断出现越界错误。

我无法使用数组。

2 个答案:

答案 0 :(得分:2)

你的问题在这里:

currentWord = cString.substring(0, spacePos);
upClowC = Character.toUpperCase(currentWord.charAt(index));

currentWord变得更短,但index仍然从0运行到字符串的长度。

一般说明:

  • 关注Java naming conventions并将方法名称更改为小写字母

  • 当您想要将某些内容与if(validWord)进行比较时,
  • true已经足够了,否则它就像要求&#34; 这是真的,这个值是真的< / EM>&#34;而不是简单的&#34; 是值true &#34;

  • 下次发布堆栈跟踪以获得更好,更快的帮助

答案 1 :(得分:0)

在你的代码中,你正在做

spacePos = cString.indexOf(" ");

然后在循环中:

currentWord = cString.substring(0,spacePos);
upClowC = Character.toUpperCase(currentWord.charAt(index));

现在,由于循环,索引将从0到字符串长度减去1的值。如果您的子字符串(currentWord)小于您的字符串 - 可能是 - ,则{{1}将尝试索引子字符串的边界,这就是你得到错误的原因。