我正在为班级做这个小硬件问题。我的程序的重点是计算用户输入中短语中的所有空白字符。在我到达我的 for 循环之前,一切都很好。我在循环中设置了一个断点,它运行良好并计算空白字符。但是当循环结束时程序崩溃并给我这个错误:
线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:5
我不太明白是否有人能指出我正确的方向。
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 ();
}
}