java中的字符串索引越界错误(charAt)
快速提问。我在程序中有以下代码:java中的字符串索引越界错误(charAt),java,charat,Java,Charat,快速提问。我在程序中有以下代码: 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++; } in
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=JOptionPane.showInputDialog(“在下面输入任何单词”)
int i=0;
对于(int j=0;j您是从[0-length]访问数组的,应该从[0-(length-1)]
inti=0;
对于(int j=0;j
更换:
j <= input.length()
j尝试以下操作:
j< input.length()
j
然后:
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++;
}
inti=0;
对于(int j=0;j
使用这个
for (int j = 0; j < input.length(); j++)
{
System.out.print(input.charAt(j));
System.out.print(" "); //don't ask about this.
}
for(int j=0;j
Java中的字符串索引(与任何其他类似数组的结构一样)是基于零的。这意味着input.charAt(0)
是最左边的字符。最后一个字符位于input.charAt(input.length()-1)
因此,您在for
循环中引用了太多元素。请将替换为(int j=0;j
替换for循环条件j为什么在循环中使用i?你不能使用j吗?在这种情况下,我使用i作为计数整数,就像在for循环中一样,因为我不希望使用for循环,然后我就这样做了……我会投票支持其他回复,但我没有必要的代表感谢你们所有人帮我完成这项工作!
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++;
}
for (int j = 0; j < input.length(); j++)
{
System.out.print(input.charAt(j));
System.out.print(" "); //don't ask about this.
}
for (int j = 0; j < input.length(); j++)
{
System.out.print(input.charAt(j));
System.out.print(" "); //don't ask about this.
}