How to count vowels and consonants and capitalizing first letter in a string while output using a method and return result

前端 未结 9 2423

If a user enters a string: hello there

it should output

Hello has 2 vowels
There has 3 consonants.

I know this is a f

9条回答
  •  伪装坚强ぢ
    2020-12-07 00:01

    Made something like this hope this helps, this will give vowels,consonants of each word

    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();
                    int count = 0;
                    int vowels = 0;
                    int consonants = 0;
                    for (String retval: string1.split(" ")){
                         for (int i = 0; i < retval.length(); i++)
                    {
                            char ch = retval.charAt(i);
                            if (ch == 'a' || ch == 'e' || ch == 'i' || 
                                            ch == 'o' || ch == 'u')
                            {
                                    vowels++;
                            }
                            else
                            { 
                                    consonants++;
                            }
                    }
                System.out.println(retval.substring(0, 1).toUpperCase() + retval.substring(1)+" has "+vowels+" vowels and "+consonants+" cosonants");
             vowels=0;
             consonants=0;
          }
    
            }
    

提交回复
热议问题