Reputation: 3324
I am working on a pig latin translator which translator the given word into pig latin. Here is the pig latin method and the isVowel method.
public static void pigLatin(String s) {
char[] array = s.trim().toCharArray();
if(isVowel(s.charAt(0)) && !Character.toString(s.charAt(0)).equalsIgnoreCase("y")){
System.out.println(s+"way");
}else {
int i = 0;
String toReturn = "";
do {
toReturn += array[i];
i++;
}while(!isVowel(s.charAt(i)) && !Character.toString(array[i]).equalsIgnoreCase("y"));
System.out.println(s.substring(i)+toReturn+"ay");
}
}
public static boolean isVowel(char c) {
char[] vowels = new char[] {'a','e','i','o','u','y'};
for(int i = 0;i<vowels.length;i++) {
if(Character.toString(vowels[i]).equalsIgnoreCase(Character.toString(c))) {
return true;
}
}
return false;
}
The problem is when I input words "BIrD" and "quiet". First one throws java.lang.StringIndexOutOfBoundsException: String index out of range: 4
The second one doesn't convert properly. Quiet prints uietqay, when it supposes to be ietquay, but that doesn't make sense because, you supposed to take all constants upto the vowel, which should mean uietquay so why is it ietquay? Can someone please point me in the correct direction?
NOTE: This is not homework.
Upvotes: 0
Views: 3038
Reputation: 11
public static String pigLatin(String a){
a=a.toLowerCase();
String [] x=a.split(" ");
int vowl=0;
String c="";
String d="";
String trans="";
for(int i=0; i<x.length; i++){
for(int j = 0;j<x[i].length();j++){
if(x[i].charAt(j)=='a'||x[i].charAt(j)=='e'||x[i].charAt(j)=='i'||x[i].charAt(j)=='o'||x[i].charAt(j)=='u'){
vowl=j;
j=x[i].length();
}
}
c=x[i].substring(0,vowl);
d=x[i].substring(vowl,x[i].length());
trans+= d+c+"ay ";
}
return trans;
}
Upvotes: 1
Reputation: 3255
Ignoring case, Is that a "BLRD" or a "bird"? Because if it has no vowels, your do-while loop doesn't terminate except by going out of bounds.
Your second case, "quiet" should be "uietqay" unless you want to add special logic to keep "qu" together. You could accomplish this in your while condition by making it uglier:
while( (!isVowel(s.charAt(i)) || isQU(s, i)) && !Character.toString(array[i]).equalsIgnoreCase("y"))
And then implement the appropriate isQU(String s, int index)
.
But I'd suggest that a little more rewriting is in order to make your code more readable. As is, I'm not quite sure why your isVowel
checks for "y" and your while condition also checks for "y". Some of the time you use array[i]
and some of the time you use charAt(i)
. This inconsistency makes your code harder to read with little or no benefit.
Upvotes: 2