1

我必须使用 Java 编写一个类代码,其中计算并打印出字母 E 的出现次数(包括两种情况)。这就是我所拥有的。

String sVerse = "As we enter our centennial year we are still young ";

System.out.println(sVerse);

int len3 = sVerse.length();
int countE = 0;

for (int d = 0; d <= len3; d++){
    char e = sVerse.charAt(d);
    d = d + 1;

    if (e == 'e' || e == 'E')
    {
        countE = countE + 1;
    }
    else
    {
        countE = countE;
    }
}

System.out.println(countE);

代码运行,字符串打印,但字符串打印后我得到这个错误:

 java.lang.StringIndexOutOfBoundsException: String index out of range: 1258
    at java.lang.String.charAt(Unknown Source)
    at Unit4plus.main(Unit4plus.java:125)
4

3 回答 3

1

你在d循环内部增加,这是你不应该的——让for循环去做就行了。<此外,您应该使用, 而不是终止循环<=

int countE = 0;
for (int d = 0; d < len3; d++) {
    char e=sVerse.charAt(d);

    if (e=='e' || e=='E') {
        countE++;
    }
}

但坦率地说,您可以只流式传输字符串中的字符以获得更优雅的解决方案:

long countE = sVerse.chars().filter(c -> c == 'e' || c == 'E').count();
于 2017-12-01T16:17:13.603 回答
1

您在第一个循环中的条件应该是:

d < len3

由于长度从 1 开始,但字符串中的字符索引基于 0。

此外,您在 for 循环中的语句 d=d+1 是无用的,并且使您迭代 2 到 2,因为您已经在 for 循环中使用

d++
于 2017-12-01T16:17:24.887 回答
0

您需要更改循环的条件,因为长度是最大索引的+1。您还将变量“d”的值增加了两次,一次在“for”循环的定义中,另一次在里面它。尝试用以下代码替换它:

        String sVerse = "As we enter our centennial year we are still young";
        int len3 = sVerse.length();
        int countE = 0;
        for (int d = 0; d < len3; d++) {
            char e = sVerse.charAt(d);
            if (e == 'e' || e == 'E')
                countE++;
        }
        System.out.println(countE); 
于 2017-12-01T16:23:37.993 回答