java - 元音计数、重复法

标签 java bluej

    public static void main(String args[])
     {
        Scanner sc = new Scanner(System.in);
        int countVowel=0;
        int countVowelA=0;
        int countVowelE=0;
        int countVowelI=0;
        int countVowelO=0;
        int countVowelU=0;
        char ch;
        String str;
        System.out.println("Please enter the string : ");
        str = sc.nextLine();
        for(int i = 0; i<=str.length(); i ++)
        {
            ch = str.charAt(i);
            if(ch == 'a' || ch =='A')
            {
                countVowelA++;                 
                countVowel++;
            }
            if(ch == 'e' || ch =='E')
            {
                countVowelE++;
                countVowel++;
            }
            if(ch == 'i' || ch =='I')
            {
                countVowelI++;
                countVowel++;
            }
            if(ch == 'o' || ch =='O')
            {
                countVowelO++;
                countVowel++;
            }
            if(ch == 'u' || ch =='U')
            {
                countVowelU++;
                countVowel++;
            }
            i++;
        }
        System.out.println("Occurances of A in given string  : " +countVowelA);
        System.out.println("Occurances of E in given string  : " +countVowelE);
        System.out.println("Occurances of I in given string  : " +countVowelI);
        System.out.println("Occurances of O in given string  : " +countVowelO);
        System.out.println("Occurances of U in given string  : " +countVowelU);
        System.out.println("Number of vowels in strings are  : " +countVowel);
    }
}

对我来说,我遇到了麻烦,比如说,如果我输入“勒布朗·詹姆斯是最好的篮球运动员”,你知道这一点。它给了我一个错误,而且它没有计算所有元音?另外,你能告诉我我的代码是否正确

最佳答案

检查下面的行

 for(int i = 0; i<=str.length(); i ++)

更改为

 for(int i = 0; i<str.length(); i ++)

为什么?

因为在 Java ,索引从零开始。当你有 i <= str.length ,它超出了字符串的范围索引,并为您提供 java.lang.StringIndexOutOfBoundsException

另一个问题,您已增加变量 i 两次。 if 子句之后的第二个是完全没有必要的,因为即使您纠正了边界问题,它也会给您错误的答案。

关于java - 元音计数、重复法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26516455/

相关文章:

java - 常见的 Java 桌面应用程序漏洞有哪些?

带星号的 Java ProcessBuilder 命令

Java 数组 : Finding Unique Numbers In A Group of 10 Inputted Numbers

java - Calendar.AM 必须是 : Calendar.(工作日)之一

bluej - 你如何在 BlueJ 中设置字体?

java - 调整图像大小 java getScaledInstance

java - 如何在 for 循环中调用函数?

java - 使用字符串 - Public int length()

java - 了解使用二进制补码写入 bluej 的程序。

java - 计算胜/负、胜率和总胜率