title: Why am I getting java.lang.StringIndexOutOfBoundsException?
body: <p>I want to write a program that prints words incrementally until a complete sentence appears. For example : I need to write (input), and output:</p>
  
  <blockquote>
    <p>I<br />
    I need<br />
    I need to<br />
    I need to write.<br /></p>
  </blockquote>
  
  <p>Here is my code:</p>
  
  <pre><code>public static void main(String[] args) {   
     String sentence = "I need to write.";
     int len = sentence.length();
     int numSpace=0;
     System.out.println(sentence);
     System.out.println(len);
  
     for(int k=0; k&lt;len; k++){
        if(sentence.charAt(k)!='\t')
           continue;
        numSpace++;
     }
  
     System.out.println("Found "+numSpace +"\t in the string.");  
  
     int n=1;
     for (int m = 1; m &lt;=3; m++) {      
        n=sentence.indexOf('\t',n-1);
        System.out.println("ligne"+m+sentence.substring(0, n));
     }
  }
  </code></pre>
  
  <p>and this is what I get:</p>
  
  <blockquote>
    <p>I need to write.<br />
    16<br />
    Found 0    in the string.<br />
    Exception in thread "main" java.lang.StringIndexOutOfBoundsException:<br />
    String index out of range: -1     at<br />
    java.lang.String.substring(String.java:1937)  at<br />
    split1.Split1.main(Split1.java:36) Java Result: 1 BUILD SUCCESSFUL<br />
    (total time: 0 seconds)<br /></p>
  </blockquote>
  
  <p>I don't understand why numSpace  doesn't count the occurrences of spaces, nor why I don't get the correct output (even if I replace numSpace by 3 for example).</p>