Java ArrayIndexOutOfBounds异常
也许我已经看了太久,因为我找不到问题,但它应该是一些简单的东西。我在线路上收到ArrayIndexOutOfBounds异常:Java ArrayIndexOutOfBounds异常,java,arrays,exception,Java,Arrays,Exception,也许我已经看了太久,因为我找不到问题,但它应该是一些简单的东西。我在线路上收到ArrayIndexOutOfBounds异常: nextWord = MyArray[i + 1].toLowerCase(); 有人知道为什么吗 String currentWord = ""; String nextWord = ""; for (int i = 0; i <= MyArray.length; i++) { // If not at the end of the ar
nextWord = MyArray[i + 1].toLowerCase();
有人知道为什么吗
String currentWord = "";
String nextWord = "";
for (int i = 0; i <= MyArray.length; i++) {
// If not at the end of the array
if (MyArray.length > 0 && i < MyArray.length) {
currentWord = MyArray[i].toLowerCase();
nextWord = MyArray[i + 1].toLowerCase(); /* EXCEPTION */
System.out.println("CURRENT WORD: " + currentWord);
System.out.println("NEXT WORD: " + nextWord);
}
}
String currentWord=”“;
字符串nextWord=“”;
对于(int i=0;i 0&&i
谢谢 因为如果i
0
运行到Array.Length-1
因此,阵列的典型循环结构为:
for (int i=0; i<array.length; i++) // do stuff
数组索引从
0
到Array.length-1
运行
因此,阵列的典型循环结构为:
for (int i=0; i<array.length; i++) // do stuff
MyArray.length-1
是数组的最后一个元素。i
的最大值,如果为MyArray.length-1,则该值将在中下降。在i+1
中增加1,得到MyArray.length
。当然,您将收到一个异常:)MyArray.length-1
是数组的最后一个元素。i
的最大值,如果为MyArray.length-1,则该值将在中下降。在i+1
中增加1,得到MyArray.length
。当然,您将收到一个异常:)对于数组MyArray
,有效索引是[0,MyArray.length-1]
。因为对于给定的i
您正在访问索引i+1
处的元素,i
的有效值是[0,MyArray.length-2]
因此,您可以:
for (int i = 0; i <= MyArray.length-2; i++) {
// no need of the if check anymore.
currentWord = MyArray[i].toLowerCase();
nextWord = MyArray[i + 1].toLowerCase();
对于(int i=0;i对于数组MyArray
,有效的索引是[0,MyArray.length-1]
。因为对于给定的i
您是在索引i+1
处访问元素,i
的有效值是[0,MyArray.length-2]
因此,您可以:
for (int i = 0; i <= MyArray.length-2; i++) {
// no need of the if check anymore.
currentWord = MyArray[i].toLowerCase();
nextWord = MyArray[i + 1].toLowerCase();
for(int i=0;i只需修复您的检查,确保您不是数组的最后一个成员。如果您是数组的最后一个成员,向其中添加一个将超出数组,因此您将获得该异常。此外,您将跳过第一个元素,并循环经过数组的末尾(由于从零开始,到长度是一个额外的循环)
for(inti=0;i
只需修复您是否位于数组的最后一个成员的检查。如果您位于数组的最后一个成员,向其中添加一个将超出数组,因此您将获得该异常。此外,您将跳过第一个元素,并循环经过数组的结尾(因为从零开始,到长度是一个额外的循环)
for(inti=0;i
删除=
。它应该是i
我仍然不明白的一件事是,在迭代时#1,当i=0,currentWord=“”和nextWord=“”。在迭代时#2,当i=1,那么currentWord和nextWord将被正确设置。我如何解决这个问题?另外,如果我还想包括并设置一个“previousWord”?除非MyArray[0]是空字符串,否则不应出现这种情况。此外,您可以添加另一个类似于我在当前word之前放置的检查,并检查I>0,并且previousWord=MyArray[I-1]。toLowerCase()啊,原来我在所有作业之前都有我的打印语句。谢谢!删除=
。它应该是I
在这里我仍然不明白的一件事是,在迭代#1中,当I=0,currentWord=”和nextWord=”时“。在迭代#2中,当i=1时,currentWord和nextWord将被正确设置。我如何解决这个问题?另外,如果我还想包含并设置一个“previousWord”呢?除非MyArray[0]是空字符串,否则不应该发生这种情况。此外,您可以添加另一个类似于我在当前word之前放置的检查,并检查i>0,以及previousWord=MyArray[i-1].toLowerCase()啊,原来我在所有作业之前都有我的书面陈述。谢谢!谢谢你的澄清!谢谢你的澄清!
for (int i = 0; i < MyArray.length; i++) {
currentWord = MyArray[i].toLowerCase();
System.out.println("CURRENT WORD: " + currentWord);
// If not at the end of the array
if (i != MyArray.length - 1) {
nextWord = MyArray[i + 1].toLowerCase();
System.out.println("NEXT WORD: " + nextWord);
}
}