如何计算元音和辅音,并在使用方法和返回结果输出时将字符串中的第一个字母大写 [英] How to count vowels and consonants and capitalizing first letter in a string while output using a method and return result

查看:162
本文介绍了如何计算元音和辅音,并在使用方法和返回结果输出时将字符串中的第一个字母大写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果用户输入字符串:你好

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆