这是上一年的考试题,有错误,但我似乎无法理解为什么?我不断收到此错误:
线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:21
public class SwimmingPool{
public static void countSpaces(String s){
int count = 0;
for(int i = 0; i <= s.length(); i++){
if(s.charAt(i) == ' '){
count++;
}
}
System.out.println("Percent of spaces is" + count /
s.length());
}
public static void main (String[] args){
String s = "lefhg aljdfgh liauh h";
countSpaces(s);
}
}