2010-10-28 70 views
1

也许我一直在寻找这个太久,因为我无法找到问题,但它应该是简单的东西。我收到一条线上的ArrayIndexOutOfBounds异常:的Java异常的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 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); 
    } 
    } 

谢谢!

回答

3

数组索引运行从0array.length - 1

典型的循环构建阵列是这样的:

for (int i=0; i<array.length; i++) // do stuff 
你的情况

,你已经得到了一个单一的位置向前看,这样避免了界外,你需要通过限制该循环一个位置:

for (int i=0; i<array.length-1; i++) // do stuff 

如果范围的循环之外的指标,在​​循环之后将有分配权值的最后currentWord

int i=0; 
for (; i<array.length-1; i++) // do stuff 
// here i == array.length - 1, provided you don't mess with i in the "do stuff" part 
+0

谢谢澄清! – littleK 2010-10-28 16:09:02

0

因为如果我< MyArray.Length,然后I + 1可以是出界。例如,如果i = MyArray.Length - 1(Last valid index),那么i + 1 = MyArray.Length,这是超出界限的。

4

MyArray.length - 1是该数组的最后一个元素。 i的最大值将在if中下降为MyArray.length - 1。你在i + 1中增加一个,所以你得到MyArray.length。当然你会收到一个异常:)

0

对于数组,有效索引是[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(); 
0

简单的解决您的支票,你是不是在数组的最后一个成员。如果你在数组的最后一个成员,向它添加一个将超出数组,因此你会得到这个异常。你也跳过了第一个元素,并循环过数组的末尾(因为你从零开始,长度是一个额外的循环)

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

删除'='。它应该是'我 2010-10-28 16:01:32

+0

对,我错过了,当我复制他的代码。谢谢 – robev 2010-10-28 17:16:30

+0

有一点我仍然不明白,在迭代#1中,当i = 0时,currentWord =“”和nextWord =“”。在迭代#2中,当i = 1时,currentWord和nextWord将被正确设置。我该如何解决这个问题?另外,如果我还想包含并设置“前一个词”呢? – littleK 2010-10-28 17:52:21