Вопрос

hey guys i'm a newby to programming in java and i'm trying to figure out why i'm getting a string out of bounds on my secondary loop. I'm trying to create a spell checker & i'm not sure maybe i'm not doing this exactly right. I'm trying to check the word of a sentence and compare it to the other array of words and char each character until end of the length of toCheck, but doesn't work :\

Any help would be greatly appreciated!! thank you in advance

    public static String suggestions (String toCheck, String [] words, Scanner kb)
   {//start
      int length=toCheck.length(),total=0, count = 0;
      for(int x = 0;x<words.length;x++)
      {
         if(words[x].charAt(0)==(toCheck.charAt(0)))
            for(int j = 0;j<length-1;j++)
            {
               if(toCheck.charAt(j)==words[x].charAt(j))
                  count++;

            }
         if(count>=((words[x].length())/2))
            total++;}

      System.out.println(total);
      //System.out.printf("Not found - %s",toCheck); 
      //System.out.println("\nChoices 1 leave as it 2. Type replacement 3 Pick one " + Arrays.toString(suggest));
      return toCheck;

   }//end of suggestions

error message shown

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.charAt(String.java:686)
at CSCD210HW4.suggestions(CSCD210HW4.java:59)
at CSCD210HW4.main(CSCD210HW4.java:44)
Это было полезно?

Решение

Why don't you use compareTo instead of manual checking for different character. It will be more easy.

For example

  count = Math.abs(words[x].compareTo(toCheck)); 
  //It will return the difference of character in both string.
  // Suppose words[x] = "abc" and toCheck = "adc" then count will be 1.

Другие советы

length is the size of the word to check.

you're trying to access words[x].charAt(j) which does not have to exist. j is the length of the string toCheck

You can use the below code:

public class check {
    public static  boolean suggestions (String toCheck, ArrayList<String> words)
    {
        for(String word: words )
        {
             return (toCheck.toLowerCase().equalsIgnoreCase(word));
        }
        return false;
    }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top