Reputation: 87
I am writing a program to find the number of vowels in each word within an array. I have the code finished, I am just unsure of what the return value should look after the if statement.
public static int vowels(char [] array, int x, int y) {
if(array[x]=='a' || array[x]=='e' || array[x]=='i' || array[x]=='o' ||
array[x]=='u' || array[x]=='y') {
y++;
}
if (x < array.length) {
x++;
vowels (array, x, y);
return ???;
} else {
return y;
}
}
Upvotes: 1
Views: 5223
Reputation: 41200
If I understand you correctly-
private static String vowelString = new String("aeiou");
public static int vowels(char [] array) {
int x=0;
for(char ch:array) {
if(vowelString.indexOf(ch)>=0)
x++;
}
return x;
}
Upvotes: 1
Reputation: 14925
Here's the solution to the program -
public class so { public static void main(String[] args) { // TODO Auto-generated method stub
char array[] = {'a', 'e', 'i', 'x', 'h', 't', 'd' };
System.out.print( vowels(array, 0, 0));
}
public static int vowels(char [] array, int x, int y) {
if(array[x]=='a' || array[x]=='e' || array[x]=='i' || array[x]=='o' ||
array[x]=='u' || array[x]=='y') {
y++;
}
Note that in x should be less than array.length-1 since its value is getting incremented. Otherwise it will throw an index out of bounds exception.
if (x < (array.length-1)) {
x++;
return vowels (array, x, y);
} else {
return y;
}
//return -1;
}
}
Cheers,
Upvotes: 0
Reputation: 25950
Sample code:
Map<String, String> vowels = new HashMap<String, String>() {
{
put("a", "");
put("e", "");
put("i", "");
put("o", "");
put("u", "");
put("y", "");
}
};
String input = "blablabla";
int counter = 0;
for (int i = 0; i < input.length(); i++) {
if (vowels.containsKey(input.charAt(i) + ""))
counter++;
}
Upvotes: 0
Reputation: 34900
Using recursion here it is a very ugly solution. It would be much more simpler, if you rewrite it so:
public static int vowels(char[] array) {
int y = 0;
for (char x : array) {
if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'y')
y++;
}
return y;
}
But if you actually need use recursion (e.g. it is your homework, and it is your task, that you must use it), then you need to fix some mistakes in your code and remove y
argument - it is unnecessary:
public static int vowels(char[] array, int x) {
int y = 0;
if (array[x] == 'a' || array[x] == 'e' || array[x] == 'i' || array[x] == 'o' ||
array[x] == 'u' || array[x] == 'y')
y++;
if (x < array.length - 1) {
x++;
y += vowels(array, x);
}
return y;
}
Upvotes: 0
Reputation: 2654
Instead of
vowels (array, x, y);
return ???;
You should return the value, computed by vowels, since it is a clean function, and doesn't has side effects:
return vowels (array, x, y);
Upvotes: 2