3 回答
TA贡献1871条经验 获得超8个赞
由于索引从0, not from 1. 因此,如果您有一个长度为 String 的字符串,4则0,1,2,3是唯一可能的索引。如果您提供的索引作为参数charAt()isless than 0或greater than or equals字符串的长度,那么您将得到StringIndexOutOfBoundsException异常。在这里你可以看到 charAt 方法是如何工作的:
public char charAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}
TA贡献1820条经验 获得超10个赞
答案是您正在迭代从 0 开始的索引。
想象一个长度为 4 的数组。它将存储 4 个项目,第一个在索引 0,第二个在索引 1,第三个在 2,最后一个在索引 3。最后一个元素的索引总是length() - 1,这就是为什么你把它作为循环中的上边界,以便不提高IndexOutOfBoundsExceptionwhile 迭代。
您可以添加一些控制台输出来查看String每次迭代的访问索引,如下所示:
public class MStringReverse {
static String getReverse(String input) {
System.out.println("Input length is " + input.length());
String reverse = "";
for(int i = input.length() - 1; i >= 0; i--) {
System.out.println("accessing index " + i + " of \"input\"");
reverse = reverse + input.charAt(i);
System.out.println("last index of \"reverse\" is now " + (reverse.length() - 1));
}
return reverse;
}
public static void main(String[] args) {
String result = getReverse("Achilis");
System.out.println(result);
}
}
添加回答
举报