title: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 269
body: <p>I am writing a program that counts the number of words in a text file, but only words that have more than 2 characters in them. It was working fine before, but all of a sudden I am getting an error</p>
  
  <blockquote>
    <p>Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 269?</p>
  </blockquote>
  
  <p>Can someone please help?</p>
  
  <pre><code>import java.io.*;
  
  class count_words {
  
      public static int countWords(String str)
      {
          int count = 1, num_of_letters = 0, final_count=1;
  
          for (int i=0;i&lt;=str.length()-1;i++)
          {
              if (str.charAt(i) == ' ' &amp;&amp; str.charAt(i+1)!=' ')
              {
                  if(num_of_letters &lt;= 2)
                  {
                      count --;
                  }
  
                  System.out.println("count is " + num_of_letters);
                  num_of_letters = 0;
                  count++;
              }
              else if(str.charAt(i) == ',')
              {
                  num_of_letters --;
              }
              else
              {
                  num_of_letters++;
              }
          }
  
          return count;
      }
  
      public static void main(String[] args){
  
          //name of file to open
          String fileName = "/Users/Chris/Desktop/comp 1 McPhee.txt";
          //reference one line at a time
          String line = null;
          int num;
  
          try 
          {
              //Filereader reads text file in the default encoding.
              FileReader filereader = new FileReader(fileName);
              BufferedReader bufferedreader = new BufferedReader(filereader);
  
              while ((line = bufferedreader.readLine()) != null) 
              {
                  num = countWords(line);
                  System.out.println(num);
              }
          } 
  
          //Always close file
          catch(FileNotFoundException ex)
          {
              System.out.println("Unable to open file '" + fileName + "'");
          }
  
          catch(IOException ex)
          {
              System.out.println("Error reading file '" + fileName + "'");
          }
      } 
  }
  </code></pre>