Reputation: 39
I am new to Java programming. My homework problem states that to Write a program that calls a method to print the number of vowels in a sentence (use ‘nextLine()’to read a sentence instead of a single word). Print the number of occurrences of each vowel (ie: the number of ‘a’s, the number of ‘e’s, etc.) Here is my program so far
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
String str = in.nextLine();
System.out.println("The number a vowels in the sentence are" + vowel(str));
}
public static String vowel(str)//I'm having trouble here
{
int len = str.length(); // Here
int count = 0;
for (int i = 0; i < len; i++)
{
char str2 = str.charAt(i);//Here
if (str2 == 'a')
count++;
}
return str2; // And finally here
}
Upvotes: 0
Views: 118
Reputation: 3467
You cannot return str2 after the for-loop, because you declared it inside, and it is invalid outside. Also it has a different data type than the method (String vs char).
Upvotes: 0
Reputation: 747
Also, use an array to stock the occurence of voyels, to handle the result easier.
Upvotes: 0
Reputation: 1500665
The problem is with your method declaration. You need to declare the type of your str
parameter, like this:
public static String vowel(String str)
Additionally, you're only declaring str2
within your loop - so you can't use it for the return statement (which is outside the loop). Given that you're trying to return a count of vowels, you should change the return type to int
anyway... and then return count
, not str2
:
public static int vowel(String str) {
... code as before apart from last line...
return count;
}
Upvotes: 10