【发布时间】:2013-11-12 15:07:38
【问题描述】:
这是上一年的考试题,有错误,但我似乎不明白为什么?我不断收到此错误:
线程“main”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);
}
}
【问题讨论】:
-
i <= s.length()... 真的,您应该至少在发布问题之前调试您的代码。
标签: java indexoutofboundsexception