Reputation: 13
I'm trying to optimize my Java code so I try things. In my search for a short way I produced the code here below. This throws an Exception
. Can you tell me why? Can't I loop through a string by a char Array?
public class Input {
public static void main(String[] args) {
String check = "Dit moet toch gewoon te doen zijn !!";
check = check.toLowerCase();
int[] counter = {0, 0, 0, 0, 0};
char[] vowel = {'a', 'e', 'i', 'o', 'u'};
int total = 0;
for (int i = 0; i < check.length(); i++)
if (check.charAt(i) == vowel[i])
counter[i]++;
for (int t : counter)
total += t;
System.out.println("Aantal klinkers: \t" + total);
}
}
Upvotes: 1
Views: 7629
Reputation: 71
for (int i = 0; i < check.length(); i++)
if (check.charAt(i) == vowel[i])
counter[i]++;
This loop goes from 0
to check.length()
; but your array vowel[]
has 5 element. So it generate array out of bound exception.
Upvotes: 2
Reputation: 1723
You could use a regex for this operation:
Pattern vowels = Pattern.compile("(?i)[aeiou]");
String check = "Dit moet toch gewoon te doen zijn !!";
Matcher matcher = vowels.matcher(check);
while(matcher.find()) {
System.out.println("found vowel: " + matcher.group());
}
Explanation of regex:
(?i)
make pattern case insensitive, [aeiou]
characters to match.
Upvotes: 0
Reputation: 118
You must have two loops One for going through each char in string and a for loop going through each vowel array like so
for (int i = 0; i < check.length(); i++)
for (int p = 0; p < vowel.length; p++)
if (check.charAt(i) == vowel[p])
counter[p]++;
Enjoy.
Upvotes: 0
Reputation: 11041
One more for the clever regex department so you don't have to make your string lowercase and lose the cases for vowels:
if (check.matches("(?i)[^a-z][a-z].*"))
System.out.println("Vowels found: " + check.replaceAll("[^a-z]+", ""));
Upvotes: 0
Reputation: 2031
Your code reads like this: For each character in "check" if character at index in "check" is character at index in "vowel"
That's probably not what you're looking for. The exception you're getting is because there are only 5 characters in "vowel" but alot in "check" (i'm not counting)
Now, I'm assuming what you're wanting to do is actually count the number of each vowel in "check"
You should actually use a nested for loop in this case.
for (int i = 0; i < check.length(); i++) {
for (int v = 0; v < vowel.length; v++) {
if (check.charAt(i) == vowel[v]) {
counter[v]++;
break;
}
}
}
Upvotes: 3