Back to General discussions forum
Hi all, I'm having a difficult time with problem 20 using the code below. For whatever reason, when I run it using JavaScript, only the first value is added to the answer line. I'm not sure what I'm doing wrong. I solved the farenheit to celsius problem in a very similar way, and did not experience this issue. My function seems to be working correctly, because when I try something like countVowels('aaahhheeennn'), it returns 6. Could someone help me out?
var counter = input();
var vowels = ['a', 'e', 'i', 'o', 'u', 'y'];
var s = new String;
function countVowels(str) {
str = str.toLowerCase();
var count = new Number;
for (i = 0; i < str.length; i++) {
if (vowels.indexOf(str[i]) !== -1) {
count = count + 1;
}
}
return count;
}
for (i = 0; i < counter; i++) {
s = s + countVowels(input()) + ' ';
}
output(s);
Hi! Judging by behavior you described probably the trouble is with reading counter
as
string and never converting it to integer? Adding parseInt
should help...
I will check this idea bit later (I'm having very poor internet connection right now, sorry)
UPD Ah, it is different thing. You use i
variable both in function and the main code,
but inside function you do not declare it (with var
) so it is reused from the global scope.
And after calling the function inside the loop it became equal to the length of the first line
I believe... You need either to use different variables, or (which is better)
for (var i = 0; ...)
inside the function.