gpt4 book ai didi

java - 如何在使用方法输出并返回结果时计算字符串中的元音和辅音并将首字母大写

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:14:53 30 4
gpt4 key购买 nike

如果用户输入字符串:hello there

它应该输出

Hello has 2 vowels
There has 3 consonants.

我知道这是一个相当简单的代码,但我有太多的想法并且感到困惑。我需要一个来确保我有 2 个方法用于 numberofVowels 和 capitalizeWord 并且都返回一个结果

我遇到了一个错误,在我计算元音后,我仍在尝试弄清楚如何利用

import java.util.Scanner;

public class Hwk9
{
public static void main (String args[])
{
Scanner stdin = new Scanner(System.in);
String string1;
System.out.println("Enter a string");
string1 = stdin.nextLine();
string1 = string1.toLowerCase();

}
public static int numberVowels(String string1)
{

int count = 0;
int vowels = 0;
int consonants = 0;
for (int i = 0; i < string1.length(); i++)
{
char ch = string1.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' ||
ch == 'o' || ch == 'u')
{
vowels++;
}
else
{
consonants++;
}
}
}
}

最佳答案

这是一个更简单的方法,希望对您有所帮助:

public static void checkVowels(String s){
System.out.println("Vowel Count: " + (s.length() - s.toLowerCase().replaceAll("a|e|i|o|u|", "").length()));
//Also eliminating spaces, if any for the consonant count
System.out.println("Consonant Count: " + (s.toLowerCase().replaceAll("a|e|i|o| |u", "").length()));
}

关于java - 如何在使用方法输出并返回结果时计算字符串中的元音和辅音并将首字母大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48693023/

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