【发布时间】:2013-08-16 19:15:44
【问题描述】:
我得到了第一个 for 循环的正确输出:for(int i=0;i<=name.length();i++),但不知道为什么我没有得到这个循环的任何输出:for(int i=name.length();i>=0;i--)。执行时我收到一条错误消息,指出索引超出范围。
我检查了错误here,但我不明白。
public class runner {
public static void main(String[] args) {
String name = "java";
System.out.println(".length method()" + name.length());// executing
// .length()
// method
System.out.println(".charAt method()" + name.charAt(5));
for (int i = 0; i <= name.length(); i++) {
System.out.println(name.charAt(i));
}
for (int j = name.length(); j >= 0; j--) {
System.out.println(name.charAt(j));
}
}
}
输出
j
a
v
a
【问题讨论】:
-
在
for循环条件中将<=更改为< -
在Java中,类名要大写(
Runner而不是runner),粘贴代码前请运行格式化程序。 -
为了简化下面的所有答案,索引从 0 开始,这意味着最大可访问索引是长度为 1。因此,索引必须在 0
标签: java