如何在使用方法输出时计算元音和辅音并将字符串中的第一个字母大写并返回结果 [英] How to count vowels and consonants and capitalizing first letter in a string while output using a method and return result
本文介绍了如何在使用方法输出时计算元音和辅音并将字符串中的第一个字母大写并返回结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果用户输入一个字符串:hello there
If a user enters a string: hello there
它应该输出
Hello has 2 vowels
There has 3 consonants.
我知道这是一个相当简单的代码,但我有太多想法并且感到困惑.我需要确保我有 2 个方法用于 numberofVowels 和 capitalizeWord 并且都返回结果
I know this is a fairly simple code but I am getting too many ideas and getting confused. I need a to make sure I have 2 methods for numberofVowels and capitalizeWord and both returns a result
我遇到了一个错误,在计算元音后,我仍在试图找出大写
I am getting an error and I am still trying to figure out to capitalize after I got counting vowels work
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++;
}
}
}
}
推荐答案
这里有一个更简单的方法,希望对您有所帮助:
Here is a simpler way of doing this, hope this helps:
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()));
}
这篇关于如何在使用方法输出时计算元音和辅音并将字符串中的第一个字母大写并返回结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文