A simple java query

R0H!T

Adept
Hi,

I am doing this assignment for my friend :p
and I am new to java [tho I had learned some basics a year ago]

anyways, one of the assignment question is "Write a program that accepts a string and finds the no of vowels in it."

now, I have written the following code:

Code:
import java.util.*;
public class vowel 
{
	public static void main(String[] args) 
	{
		Scanner a = new Scanner(System.in);

		System.out.println("Enter a string:");
		String s = a.next();
		int i,count = 0;

		for (i = (s.length() - 1); i >= 0; i--)
		{
			if (s.charAt(i) == 'a' || s.charAt(i) == 'e' || s.charAt(i) == 'i' || s.charAt(i) == 'o' || s.charAt(i) == 'u')
			{
				count++;
			}
			else if (s.charAt(i) == 'A' || s.charAt(i) == 'E' || s.charAt(i) == 'I' || s.charAt(i) == 'O' || s.charAt(i) == 'U')
			{
				count++;
			}
		}
		System.out.println("The number of vowels in the above string: " + count);
	}
}

now it prints the number of vowels only for the first word i.e. it does not consider anything after a white space.

so if I type say 'abc' it prints 1, but for 'abc abc' also it prints 1 :huh:

Sorry, for asking such a simple question :ashamed:
 
The String s = a.next(); gives you the first string in the sentence inputted. You need to invoke next() in a loop to iterate over every string in the sentence.
 
@ vicente

Thanks for reply.

I got the answer already :tongue:
Instead of next() I should have used nextLine()
problem solved!
 
Back
Top