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:
Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: 5
I don’t quite understand if someone could point me in the right direction.
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<=length; i++ ){
if(phrase.charAt(i)==' '){
countBlank++;
}
}
// Print the results
System.out.println ();
System.out.println ("Number of blank spaces: " + countBlank);
System.out.println ();
}
}
To elaborate and explain the answers given a bit:
The condition for your loop:
Instructs the program to do the following:
The array that you are iterating over, by definition, will have to fail at step #4. Since arrays are indexed starting at 0, an array with ‘n’ elements will have a maximum index of ‘n-1’.