I've looked at plenty of questions related to mine here but they're all using different methods to the method I have to use. I'm aware it's a very long winded way to find out when there are simpler ways but I'm just following instructions.
Why doesn't the below code work? The function checks if it's vowel. Then the input is checked to see if it's length is 1. If it's 1, call the function. If it's greater than 1, ask for another input until the length is 1.
I see now that boolean doesn't exist in JS. I guess this question is invalid now!
function isVowel(x){
boolean result;
if(x == "A" || x == "E" || x == "I" || x == "O" || x == "U" ) {
result = true;
}
else{
result = false;
}
return result;
}
var input;
input = prompt("Enter a character ");
input = input.toUpperCase();
if(input.length == 1){
isVowel(input);
}
}
else{
while(input.length != 1){
prompt("Enter a character ");
if(input.length == 1){
isVowel(input);
}
}
}
alert(isVowel(input));
You're calling isVowel in three places, and just throwing away the return value in the first two. If you want to see the return value in the first two places, show it (via alert as in your last example, or any of several other ways).
There are other issues as well:
As devqon points out, you've used boolean rather than var, so the code won't parse
Any time you find yourself writing:
var result;
if (condition) {
result = true;
} else {
result = false;
}
return result;
...stop and make it:
var result = condition;
return result;
So for isVowel:
function isVowel(x) {
var result;
result = x == "A" || x == "E" || x == "I" || x == "O" || x == "U";
return result;
}
(You can, of course, make that a one-liner, but it's easier to debug this way.)
You have an extra } after your if block (reasonable, consistent formatting would have make that obvious)
Your while loop will never end, because you never update input with the return value of the prompt
Rather than an if followed by a while, use do-while
Here's an updated version with just those changes
function isVowel(x) {
var result;
result = x == "A" || x == "E" || x == "I" || x == "O" || x == "U";
return result;
}
var input;
do {
input = prompt("Enter a character ");
if (input.length == 1) {
alert(isVowel(input));
}
} while (input.length != 1);
The answer can be one line and is short and sweet. See below.
function isVowel(x) {
return ("aeiouAEIOU".indexOf(x) != -1);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With