Counting Blank Characters in Phrase - Java
<p>I'm doing this small HW problem for class. The point of my program is to count all the blank characters in a phrase from user input. Every thing is fine until I reach my for loop. I've put a break point at the loop and it runs fines and counts the blank character. But when the loop ends the program crashed and gives me this error:</p>

<p>Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5</p>

<p>I don't quite understand if someone could point me in the right direction. </p>

<pre><code>import java.util.Scanner;
public class Cray {
    public static void main(String[] args){
              String phrase;    // a string of characters
              int countBlank;   // the number of blanks (spaces) in the phrase 
              int length;       // the length of the phrase
              char ch;          // an individual character in the string

            Scanner scan = new Scanner(System.in);

              // Print a program header
              System.out.println ();
              System.out.println ("Character Counter");
              System.out.println ();

              // Read in a string and find its length
              System.out.print ("Enter a sentence or phrase: ");
              phrase = scan.nextLine();
              length = phrase.length();

              // Initialize counts
              countBlank = 0;

              // a for loop to go through the string character by character
              // and count the blank spaces

              for(int i =0; i&lt;=length; i++ ){
                  if(phrase.charAt(i)==' '){
                      countBlank++;

              }
              }


              // Print the results
              System.out.println ();
              System.out.println ("Number of blank spaces: " + countBlank);
              System.out.println ();
            }
        }
</code></pre>
