-3

我在线程“main”java.lang.StringIndexOutOfBoundsException 中得到 String out of range 异常:String index out of range: 5 at java.lang.String.charAt(String.java:658) at java.lang.String.charAt(String.java:658) at Lab6.DataSentinelWhile3.main(DataSentinelWhile3 .java:24)

public static void main(String[] args) {
        String sentence;
        char ch = 'a';
        int ind = 0, upperLetter=0, lowerLetter=0, digits=0, punctuation=0;

        Scanner input = new Scanner(System.in);
        System.out.print("Please enter a sentence (full-stop to terminate):");
        sentence = input.nextLine();
        while(ch != '.') {
            if(ch >= 'a' && ch <= 'z')
                lowerLetter++;
            else if(ch >= 'A' && ch <= 'Z')
                upperLetter++;
            else if(ch >= '0' && ch <= '9')
                digits++;
            else
                punctuation++;

            ind++; //increase the index of the sentence by 1
            ch = sentence.charAt(ind); //extract every character from sentence
        }

        System.out.print("\n\n*****Lexical Analysis of your Sentence*****" + 
        "\nLowercase letters: " + lowerLetter +
        "\nUppercase letters: " + upperLetter +
        "\nDigits: " + digits +
        "\nPunctuation symbols: " + (punctuation+1));
        input.close();
    }
4

3 回答 3

1

试试这个循环

而(ind <句子.长度){

}

改变这个

ch = sentence.charAt(ind); IND++;

于 2013-11-10T18:24:55.727 回答
1

尽可能使用forloop,出错的可能性减少10倍:,for while循环:

     ind i = 0; 
     while(ind < sentence.length){
        ch = sentence.charAt(ind);
        if(ch == '.') break;
        if(ch >= 'a' && ch <= 'z')
            lowerLetter++;
        else if(ch >= 'A' && ch <= 'Z')
            upperLetter++;
        else if(ch >= '0' && ch <= '9')
            digits++;
        else
            punctuation++;
        ind++;
     }
于 2013-11-10T18:27:21.117 回答
0

while(ch != '.')

您应该在字符串长度上设置循环,如果sentence不以最后一个点结尾,"."它就不会停止。

于 2013-11-10T18:22:38.047 回答