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/