I created some methods to try to do this. The first was a method to determine if the first letter was a vowel and return true if it was and false if not. here is the code:
private boolean isVowel(char let)
{
if(let == 'e' || let == 'a' || let == 'i' || let == 'o' || let == 'u' || let == 'A' || let == 'E' || let == 'I' || let == 'O' || let == 'U' )
{
return true;
}
else
{
return false;
}
}
the second method determined what and how to add the letters at the end. If the word has a vowel in front, add -ay. If not, put the first letter to the back and see if it is the same word as the original. If it is, add -yay to the end. If not, recursively call itself to see if it has a vowel in front. Here is the code:
private String fixWord(String word)
{
final String original = word;
String endWord;
String word2;
if(isVowel(word.charAt(0)) == true)
{
endWord = word + "yay";
return endWord;
}
else
{
word2 = word.substring(1) + word.charAt(0);
if(word2.equals(original) == true)
{
endWord = original + "ay";
return endWord;
}
else
{
endWord = fixWord(word2);
return endWord;
}
}
}
The last method took a given sentence and transformed all the words to pig latin using fixWord. If the string is one word, it used fixWord on it and returned the result. If not, it used fixWord on the first word (as determined by str.indexOf(" ")) and sent the rest of the sentence back to splitWords method.
here is the code:
public String splitWords(String str)
{
String word = str.substring(0,str.indexOf(" ") - 1);
String otherWords = str.substring(str.indexOf(" ") + 1,str.length());
String result;
if (str.indexOf(" ") == str.length())
{
result = fixWord(word);
}
else
{
result = fixWord(word) + splitWords(otherWords);
}
return result;
}
all of this was use in the pigLatin method, shown here: public String pigLatin(String str)
{
String result;
clean(str);
str = str.toLowerCase();
str = str + " ";
result = splitWords(str);
return str;
}
the clean method simply replaces all puncuation with blanks and trims the string.So with all this, I used a seperate tester file to see if it works. I tested the string "Good people eat pizza" and got the following errors:
Process started >>> Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -2 at java.lang.String.substring(String.java:1937) at StringUtil.splitWords(StringUtil.java:76) at StringUtil.splitWords(StringUtil.java:85) at StringUtil.splitWords(StringUtil.java:85) at StringUtil.splitWords(StringUtil.java:85) at StringUtil.splitWords(StringUtil.java:85) at StringUtil.pigLatin(StringUtil.java:70) at StringTester.main(StringTester.java:21) <<< Process finished.
what is wrong? This is really irritating to me becuase it took me a couple hours to conceive this code and it just won't work. Can anyone help with this problem and make suggestions?
note: i will attach java file and tester
Attached Files
Edited by Roger, 05 December 2010 - 08:37 AM.
added code tags


Sign In
Create Account


Back to top









