title: How would I get only the end result printed while also fixing the runtime error
body: <p>I'm pretty new when it comes to coding in java (or coding in general), and I want the code below to print out only the end result (3), but it prints everything beforehand too, then once it reaches the end it gives me a runtime error</p>
  <pre><code>package programs;
  
  public class practice2 
  {
      public static void main(String [] args)
      {
          //create a program that counts spaces in a string
          String sentence = &quot;test if this works&quot;;
  
          int count = 0;
          for(int i = 0; i &lt;= sentence.length(); ++i)
          {
              String space = sentence.substring(i, i+1);
              if(space.equals(&quot; &quot;))
              {
                  count = count + 1;
              }
              System.out.println(count);
          }
      }
  }
  </code></pre>