如果用户输入字符串: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/19661199/