a) Write a method named firstVowel that takes a string named word as parameter a
ID: 3724174 • Letter: A
Question
a) Write a method named firstVowel that takes a string named word as parameter and returns the index at which the first vowel occurs. For example, firstVowel("apple") should return 0, firstVowel("trash") returns 2. If there is no vowel in word, returns -1.
b) Write a method named pigLatin that takes a string names word as parameter and returns the pig latin translation of word. You may assume that word contains at least one vowel. Note that while translating into pig latin, the first task is to compute the index at which the first vowel appears. We can achieve this task by calling firstVowel. Pig Latin is a constructed language that takes the first consonant cluster of an English word, moves it to the end of the word and suffixes with an "ay". E.g. pig in pig Latin in igpay, trash is ashtray, and apple is appleay. Below is partially implemented method:
public static String pigLatin(String word){
int vowelPos = firstVowel(word);
// your work starts here
}
Explanation / Answer
Methods.java
public class Methods {
public static void main(String[] args) {
System.out.println(firstVowel("apple") );
System.out.println(firstVowel("trash") );
System.out.println(pigLatin("apple"));
}
public static int firstVowel(String word) {
word = word.toLowerCase();
for(int i=0;i<word.length();i++) {
if(word.charAt(i) == 'a' || word.charAt(i) == 'e' || word.charAt(i) == 'o' || word.charAt(i) == 'i' || word.charAt(i) == 'u') {
return i;
}
}
return -1;
}
public static String pigLatin(String word){
int vowelPos = firstVowel(word);
String s = "";
// your work starts here
if (vowelPos == -1) { // if no vowel
s = word; // add words without changing
} else if (vowelPos == 0) { // if first character is a vowel
s= word + "ay";
} else {
String cons = word.substring(0, vowelPos); // beginning consonant up to first vowel and move to end of the word
s = word.substring(vowelPos) + cons + "ay";
}
return s;
}
}
Output:
0
2
appleay
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.