1

I have a program that gives the following output:

Enter a Sentence: I am new to java

I

am

new

to

java

Number of vowels in: I am new to java = 6

My problem is that i need to get the vowels in each word of the sentence entered by the user.

For e.g. the output should be something like:

Enter a Sentence: I am new to java

I (1)

am (1)

new (1)

to (1)

java (2)

Number of vowels in: I am new to java = 6

I am using .split() to separate sentence entered and switch /.charAT statements for vowel checking.

Can someone please help me achieve this outcome?

Community
  • 1
  • 1
user2348633
  • 13
  • 1
  • 4
  • You gave what the final output should look like, but you also need to detail what you are getting and how you are getting it. – Guvante May 03 '13 at 23:47
  • I am getting user input using: Scanner input = new Scanner(System.in); String sentence; System.out.print("Enter a Sentence: "); sentence = input.nextLine(); SentenceSplit(sentence); //method made to split user input – user2348633 May 04 '13 at 00:08
  • Don't forget *Y* for example "the sky is beautiful today." The standard vowels are A E I O U and *Sometimes* Y. – Raystorm May 04 '13 at 00:54
  • take a look at here String based algorithm questions will help you much http://bekoc.blogspot.com/2012/07/in-this-post-i-try-to-implement.html – berkay May 04 '13 at 09:50

3 Answers3

2

The whole solution only needs a couple of lines of code:

for (String word : sentence.split(" +"))
    System.out.println(word + " (" + 
      word.replaceAll("[^aeiouAEIOU]", "")
      .length() + ")");

The way it works is the call to replaceAll() removes all non-vowels, so what remains is only vowels, then you simply take the length of that vowel-only String.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
1

I would suggest to build one String and loop through every char and check for a vowel.

String test = "I am new to Java";
int vowels = 0;

for (char c: test.toLowerCase().toCharArray()){
    if(c == 'a' || c =='e' || c=='i' || c=='o' || c=='u' ){
        vowels++;
    }
}
System.out.println(test + " Contains: " +vowels +" Vowels");
Kuchi
  • 4,204
  • 3
  • 29
  • 37
0
String n = "I am in Madurai";
int count = 0;
char c[] = new char[n.length()];
n.getChars(0, n.length, c, 0);

for(int i = 0; i < c.length; i++) {
    if (c[i] == 'a' || c[i] == 'e' || c[i] == 'i' || c[i] == 'o' || c[i] == 'u')
        count++;
}
System.out.println("Number of vowels in a given sentence: " + count);

Output:

Number of vowels in a given sentence: 7
kriegaex
  • 63,017
  • 15
  • 111
  • 202
T.B.Nanda
  • 1
  • 1