2012-05-19 23 views
1

我一直在使用this-1解析了一段时间,并想知道是否有一种方法可以在不使用-1的情况下更正for循环数组outoutbounds。请指教?ArrayOutOfBounds异常

for(int i = 0; i < hand.length - 1 ; i++) 
     { 
      if(this.hand[i].getRank() == this.hand[i + 1].getRank()) 
       return true; 
     } 
+4

当然,不要在循环中使用'i + 1'。 –

+0

这个解决方案有什么问题? – Tudor

+0

'i + 1'导致arrayindexoutof bounds –

回答

-2

记住,如果你想遍历集合中的所有项目,您可以使用for-each形式:

for (YourClass item : collection) { 
    // do something with item 
} 

http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html

编辑:只是显示方式使用迭代器。

该方法的
int nextToCompare = 1; // the index of the next item in the array to compare with the current item 
for (Item item : this.hand) { 
    if (nextToCompare < this.hand.length // checks if there is next item to compare 
      && item.getRank() == this.hand[nextToCompare++].getRank()) { 
     return true; 
    } 
} 
return false; 

一个缺点是,它迭代槽整个阵列,而不是在n - 1元件。

我认为您发布的方法实际上是一个很好的解决方案,就效率和清晰度而言。

+0

我没有downvote,但我不确定没有更多的细节,这解决了OP的代码片段的问题的根源。 –

+0

也没有downvote,但这*不*解决OP的问题。他们想要访问'i + 1'元素将遍历数组,除非您创建索引,否则这是'for-each'循环不可能实现的。在这种情况下,你可能会使用传统的'for'循环。 –

+0

我也没有downvote(?)。但是,是的,后来我意识到真正的问题,为什么这不是一个解决方案。我仍在想方设法改进我的答案来解决问题,但也许它成为有史以来最糟糕的例子。也许这会鼓励提问者保持他的实际方法:P否则,我会删除我的答案。 – Chopin

2

假设秩是int

int prevRank = this.hand[0].getRank(); 
    for(int i = 1; i < hand.length; i++) 
    { 
     int currentRank = this.hand[i].getRank(); 
     if(currentRank == prevRank) 
      return true; 
     prevRank = currentRank; 
    } 
2

你可以检查i +1元素试图从阵列读取之前存在。

像这样的工作:

for(int i = 0; i < hand.length; i++) 
     { 
      if(i + 1 < this.hand.length && this.hand[i].getRank() == this.hand[i + 1].getRank()) 
       return true; 
     } 

虽然我不认为这是一定比你有什么更好的已经。也许有人可能会说我的版本更加明确,但我会说你已经很好。

+0

'this.hand.length =手时才为真。长度“,它永远不会因为for循环。 – Jeffrey

+0

你仍然没有解决你的情况。 'i'永远不能等于'hand.length',因为一旦这样做,for循环就会退出。 – Jeffrey

+0

@Jeffrey是的,我真的把自己变成了一个向后的状态,在左边有'hand.length'。查看我的编辑 –