0
public String phraseToPigLatin()
{
    String phrase = text;

    String result = "";
    
    
    int m = 0;

    for (int i = 0; i < phrase.length(); i = i + m){

        if (Character.isLetter(phrase.charAt(i)) == false) { //this is the line number that the compiler says for the error

            result += phrase.charAt(i);
            m = 1;
            
            
        } else {

            String w = extractWord(i);
            String tr = wordToPigLatin(w);

            if (w.length() == 2){
                m = 2;
            } else if(w.length() == 1){
                m = 1;
            }
            else {
                m = tr.length()-1;
            }
            
            result = result + tr + " ";    

        }
    }

    
    return result; 
}

My extractWord method:

public String extractWord(int i){

    String word = text;
    String result = "";
    int start = 0;
    int end = 0;

   for (int n = i; n >= 0; n--){

        if (Character.isLetter(word.charAt(n)) == false) {

            start = n + 1;
            break;

        }

   }
   for (int n = i+1; n < word.length(); n++){

        if (!(Character.isLetter(word.charAt(n)))){

            end = n;
            break;
        }
   }
   result = word.substring(start,end);
   return result; 

}

So basically my extractWord method returns the word in a String whenever it locates a letter. It should return the word from that letter up till the last letter before punctuation or space ect.

However when I'm calling it in phraseToPigLatin method, it's giving me an index out of bounds exception.

I'm pretty sure that my wordToPigLatin method is correct as it all it is doing is taking the word and converting it. So I didnt include the code for that method.

Could there be a problem with my for loop (m variable) in my main method?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578

1 Answers1

1

The substring method should throw your exception.

IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.
public String extractWord(int i){
...
   result = word.substring(start,end); 
...
}

I think the problem is that you set both the start and end index to 0. So if in your first loop you fulfill the if condition you will set the start to a value. After that in the 2nd loop, if your if condition is always false then your end index remains 0. Therefore you will get the Exception.

It can happen for the last word of your string.

You can fix it by initializing the end variable to the length of the word.

String word = text;
String result = "";
int start = 0;
int end = word.length(); // <--- fix
Zsolt Toth
  • 39
  • 2