如果用户输入一个字符串:你好
它应该输出
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,string,return-value,methods
来源: https://codeday.me/bug/20190927/1824996.html