Java中的字符串索引越界错误(charAt)

3

快速提问。我在一个程序中有这段代码:

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++;
}   
  • Input 是用户输入的内容。
  • i 是一个整数,其值为0。

运行代码时出现以下错误:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6
at java.lang.String.charAt(Unknown Source)
at program.main(program.java:15)

如果我把 charAt 中的 int 改成0而不是 i,则不会产生错误...
应该怎么解决?问题出在哪里?


1
你为什么在循环中使用i?难道不能用j吗? - Karura91
在这种情况下,我使用i作为计数整数,就像在for循环中一样,因为我没有预期要使用for循环,但后来我用了... - Kyle
我会投票支持其他回复,但我还没有足够的声望。 - Kyle
感谢你们所有人帮助我解决这个问题! - Kyle
7个回答

9

替换:

j <= input.length()

... with ...

j < input.length()

Java中,String字符索引是以0为基础的,因此您的循环终止条件应为input的长度-1。

目前,在终止之前的倒数第二次迭代时,循环引用了input字符,其索引等于input的长度,这会抛出StringIndexOutOfBoundsException(一个RuntimeException)。


3
在Java中,字符串索引(就像任何其他类似数组的结构)是以零为基础的。这意味着input.charAt(0)是最左边的字符,而最后一个字符位于input.charAt(input.length() - 1)
因此,在您的for循环中,您引用了太多的元素。将<=替换为<即可解决问题。如果您将代码移植到具有无符号类型的C ++中,则使用另一种方式(<= input.length() - 1)可能会带来麻烦。
顺便说一下,Java运行时发出的异常和错误消息非常有帮助。请学会阅读和理解它们。

2

使用j < input.length()替换for循环的条件j <= input.length(),因为在Java中字符串采用从0开始的索引。 例如,字符串"india"的索引将从0到4开始。


0

你正在访问数组的[0-length],应该从[0-(length-1)]访问

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++;
}

0

请尝试以下方法:

j< input.length() 

然后:

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++;
} 

0
使用它;
for (int j = 0; j < input.length(); j++)
{
    System.out.print(input.charAt(j));
    System.out.print(" "); //don't ask about this.
}

0
for (int j = 0; j < input.length(); j++)
{
    System.out.print(input.charAt(j));
    System.out.print(" "); //don't ask about this.
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接