gpt4 book ai didi

java - 找到一个句子中所有元音的出现

转载 作者:行者123 更新时间:2023-11-30 08:59:50 25 4
gpt4 key购买 nike

我正在编写代码,在我写的句子中找到所有元音 '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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com