快问.我在程序中有这个代码:
input = JOptionPane.showInputDialog("Enter any word below")
int i = 0;
for (int j = 0; j <= input.length(); j++)
{
System.out.print(input.charAt(i));
System.out.print(" "); //don't ask about this.
i++;
}
Run Code Online (Sandbox Code Playgroud)
i 是一个值为0的整数,如图所示运行代码会产生此错误:
线程"main"中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围: 在program.main的
java.lang.String.charAt(未知源)
处为6 (program.java:15)
如果我charAt int改为0而不是i,它不会产生错误......
可以做什么?问题是什么?
更换:
j <= input.length()
Run Code Online (Sandbox Code Playgroud)
...... ......
j < input.length()
Run Code Online (Sandbox Code Playgroud)
Java String字符索引是从0开始的,因此循环终止条件应该是input's长度 - 1.
目前,当你的循环在终止之前到达倒数第二次迭代时,它引用input一个等于input's长度的索引处的字符,这会抛出StringIndexOutOfBoundsException(a RuntimeException).