/** * Returns the index within s of the first vowel (\'a\', \'e\', \'i\', \'o\',
ID: 668216 • Letter: #
Question
/**
* Returns the index within s of the first vowel ('a', 'e', 'i', 'o', 'u' or an upper-case version) that occurs in
* s. If there is no vowel in s, returns -1.
*
* For example, the method should return 0 for "Apple", 1 for "hello", 2 for "slope", 3 for "strength", and -1 for
* "xyzzy".
*
* IMPLEMENTATION NOTE: This method is already completely implemented. There is no need for you to change anything.
*/
public static int firstVowelIndex (String s)
{
int i = 0;
while (i < s.length())
{
if (isVowel(s.charAt(i)))
{
return i;
}
i = i + 1;
}
return -1;
}
Explanation / Answer
public class HelloWorld{
public static void main(String []args){
System.out.println(firstVowelIndex("Apple"));
System.out.println(firstVowelIndex("slope world"));
}
public static int firstVowelIndex (String s)
{
int i = 0;
while (i < s.length())
{
if (isVowel(s.charAt(i)))
{
return i;
}
i = i + 1;
}
return -1;
}
public static boolean isVowel(char c)
{
c = Character.toLowerCase(c);
return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.