1

I have been using this - 1 resolution for a while now, and was wondering if there is a way to correct the for loop arrayoutofbounds without the use of -1. Please advise?

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

3 回答 3

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;
    }
于 2012-05-19T15:30:31.777 回答
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;
        }

虽然我认为它不一定比你已经拥有的更好。也许有人会争辩说我的版本更明确,但我会说你已经拥有的就可以了。

于 2012-05-19T15:30:35.477 回答
-2

Remember, if you want to iterate over all the items in a collection, you can use the for-each form:

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

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

EDIT: just to show a way to use the iterator.

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;

One cons of this method is that it iterates trough the entire array, rather than over n - 1 elements.

I think the method you posted is actually a good solution, in terms of efficiency and clarity.

于 2012-05-19T15:28:57.860 回答