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

标签 java string methods return-value

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

相关文章:

Java 负向前瞻不起作用

Java:在类实例上调用时不能从静态上下文引用非静态变量

java - 我需要有关 Java JFrame 的一些帮助

java - 从 RecyclerView 中移除对象

java - 从不断变化的字符串中获取子字符串

python - 如何在 Python 中将类方法应用于我自己的类的属性

c - 在函数中传递字符串 (C)

javascript - 如何在javascript中正确转换html?

javascript - 如何从对象内部访问 vuejs 方法? (Vuejs 2)

c# - 如何在不退出程序的情况下退出方法?