I have a project that instructs to create a java class with 2 methods: one that translates a word to pig latin, another that translates a whole sentence to pig latin. I am supposed to go about this by extracting each word from a sentence, put it through my word translate method, and return the finalized sentence with each translated word.
I cannot use function such as String.split, and other shortcut functions.
My code looks like this:
public String translateWord (String word ) {
if (word.charAt(0) == 'q' && word.charAt(1) == 'u') {
return word.substring(2) + "quay";
}
else if ( word.charAt(0) == 'a' || word.charAt(0) == 'e' || word.charAt(0) == 'i' || word.charAt(0) == 'o' || word.charAt(0) == 'u') {
return word + "way";
}
else
return word.substring(1) + word.charAt(0) + "ay";
}
public String translateSentence ( String sentence ) {
String finalStr, temp;
int index = sentence.indexOf(" ");
temp = sentence.substring ( 0, index );
finalStr = translateWord(temp);
for ( int i=index+1; i < sentence.length()-2; i++ ) {
if ( sentence.substring(i, i+1).equals(" ")) {
temp = sentence.substring(i+1, sentence.indexOf( " ", i+1) ) ;
finalStr = finalStr + translateWord(temp);
}
}
return finalStr;
}
}
These are the messages appearing:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 10, end -1, length 18
at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3756)
at java.base/java.lang.String.substring(String.java:1902)
at PigLatin.translateSentence(PigLatin.java:25)
at driver.main(driver.java:6)
There are no problems with the word method, it's just there for reference. However, can anyone offer any explanation for why the sentence method does not work and help on how to fix it?
Thanks in advance, let me know if any further explanation is needed.