# Thread: Is there a way to clean up this recursion code?

1. Member
Join Date
Sep 2009
Posts
80
Rep Power
0

## Is there a way to clean up this recursion code?

Ok, so I wrote a program to count the number of vowels in a user inputted string.

The program works great. However, I was wondering if there was a way to clean my recursion method up, trying to get things as simple as possible if this isn't it. Need to work on cleaning my code up.

Here is the program:

Java Code:
```//Program to test vowel count

import java.io.*;
import java.util.*;

public class VowelCount
{

static int countVowels(String s)
{
if (s.length() == 0) return 0;
int tailResult = countVowels(s.substring(1));
switch (s.charAt(0))
{
case 'a': case 'A':
case 'e': case 'E':
case 'i': case 'I':
case 'o': case 'O':
case 'u': case 'U':

return tailResult+1;
default:
return tailResult;
}
}

public static void main(String[] args) throws IOException
{

String s;

System.out.println("Please enter a string of letters: ");
System.out.println("The string you entered is: " + s);
countVowels(s);
System.out.println("The number of vowels in the string is: " + countVowels(s));
}
}```

2. There are several ways to do this.

Method 1: For each character in the string, check if it's a vowel, and keep a running total.

Java Code:
```static int countVowels(String s)
{
int vowelCount = 0;

for (int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);

if (c == 'a' || c == 'e' || c == 'i' || c=='o' || c == 'u'
|| c == 'A' || c == 'E' || c == 'I' || c =='O' || c=='U')
{
vowelCount++;
}
}

return vowelCount;
}```
This method differs from yours in that instead of recursively checking the end of the string, you check each character.

Method 2: Use a regular expression.

I'm a regex maniac, and use it for most of my parsing needs, since it's usually shorter code, and easier to modify.

Java Code:
```static int countVowels(String s)
{
int vowelCount = 0;

// matches an 'a', 'e', 'i', 'o' or 'u'
// (the "(?i)" means case-insensitive (that is, upper-case vowels too)
Pattern vowel = Pattern.compile("(?i)[aeiou]");
Matcher matcher = vowel.matcher(s);

while (matcher.find()) {
vowelCount++;
}

return vowelCount;
}```

Also, as a note, this line does nothing, since you don't store the value.
Java Code:
`countVowels(s);`

Instead, you might want to store the value.
Java Code:
```int vowelCount = countVowels(s);
System.out.println("The number of vowels in the string is: " + vowelCount);```

3. Member
Join Date
Sep 2009
Posts
80
Rep Power
0
ok, thanks, much appreciated.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•