我正在编写代码,查找我编写的句子中的所有元音 'a' 'i' 'u' 'e' 'o'
并对其进行计数。
代码将忽略元音的大小写(大写或小写)。由于我不知道如何使元音计数不区分大小写,因此我只是将所有文本转换为小写并计算元音。我想知道是否有另一种方法可以做到这一点,而无需将所有大写字母文本转换为小写并计算元音。谢谢大家的意见,我真的很感激。这是我的代码。
import java.util.Scanner;
public class VowelCount
{
public static void main(String[] args)
{
//create scanner object
Scanner input = new Scanner (System.in);
//create vowel array
char[] vowel = new char[]{'a', 'e', 'i', 'o', 'u'};
int[] countVowel = new int[5];
String yourSentence;
//print message
System.out.print("Enter your word here:");
//set word entered as next input
yourSentence = input.nextLine();
String actualSentence = yourSentence.toLowerCase();
for (int j = 0; j < actualSentence.length(); j++)
{
char c =actualSentence.charAt(j);
if(c=='a')
countVowel[0]++;
else if(c=='e')
countVowel[1]++;
else if(c=='i')
countVowel[2]++;
else if(c=='o')
countVowel[3]++;
else if(c=='u')
countVowel[4]++;
}
for (int i = 0; i <countVowel.length; i++)
{
System.out.println("Count of vowel " + vowel[i] + "=" + countVowel[i]);
}
}
}
最佳答案
您将输入的yourSentence
更改为大写
String newResult = changeCase.toUpperCase();
然后询问最后一个句子是否包含您想要的任何字符。
这完全不是你想要做的。
我将为您提供一个示例解决方案,但您还可以做更多事情。
String newResult = changeCase.toUpperCase();
if(newResult.contains("A") ||newResult.contains("E") || newResult.contains("O") || newResult.contains("I") || newResult.contains("U"))
// Your code
现在,如果你想计算它,你可以使用 indexOf
并删除出现的次数:
while(newResult.indexOf("U") > -1)){
counter++
newResult.replaceFirst("U", "!");
}
关于java - 查找句子中所有元音的出现情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27086402/