title: How to fix index out of range error?
body: <p>I'm a beginner java programmer and I am trying to make a program which sorts a string into alphabetical order, this code is messy but I am receiving a range out of index error when it eliminates half the string. I am sure this is due to the i being incremented and the l being reduced but I am not sure of a fix, help would be appreciated, and I am not allowed to use the sort function. </p>
  
  <pre><code>import java.util.Scanner;
  import java.util.ArrayList;
  
  public class Question6{
      public static void main(String[] args){
          Scanner in = new Scanner(System.in);
          System.out.println("Please enter a string");
          String user = in.nextLine();
      int l = user.length();
      //System.out.println(l);
      int i = 0;
      System.out.println("Length is " + user.length());
      ArrayList&lt;Character&gt; chars = new ArrayList&lt;Character&gt;();
      //System.out.println(first);
      while (l &gt; 0){
          char first = user.charAt(0);
          ArrayList&lt;Character&gt; earliest = new ArrayList&lt;Character&gt;();
          earliest.add(first);
          char char1 = user.charAt(i);
          if (char1 &lt;= earliest.get(0)){
              earliest.remove(0);
              earliest.add(char1);
              user = user.substring(0, i) + user.substring(i+1);
              chars.add(char1);
              System.out.println("earliest in loop " + earliest.toString());
              System.out.println("chars in loop " + chars.toString());
              System.out.println("string is now " + user);
              System.out.println(" ");
              i = i+1;
              }
          else{
              chars.add(first);
              System.out.println("chars in else " + chars.toString());
              i = 0;
          }
          l = user.length();
      }
  
      System.out.println("done ");        
  }
  }
  </code></pre>
  
  <p>Error is </p>
  
  <pre><code>Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
      at java.lang.String.charAt(Unknown Source)
      at Question6.main.(Question6.java:19)
  </code></pre>
  
  <p>This is with the String "Stack" as input</p>