【发布时间】:2017-11-28 02:32:53
【问题描述】:
Card 是一个对象,deck 是一个包含这些卡片的数组。我试图在牌组中找到给定卡片对象的所有位置,并将所有这些位置存储在一个新数组中,然后返回该新数组。
我目前的搜索方法是这样的:
public int[] search(Card c)
{
int length = 0;
for (int x = 0 ; x < deck.length ; x++) // look through an array
{
if (deck[x].equals(c)) // value found in the array
{
length++; //update length
}
}
int[] temp = new int[length]; //create new int array with that length
for (int x = 0 ; x < deck.length ; x++) // look through the old array again
{
if (deck[x].equals(c)) // value found in that array
{
for (int y = 0 ; y < temp.length ; y++) //go through new array
{
temp[y] = x+1; //add the position to new array
}
}
}
return temp;
}
我这样称呼它:
int[] pos = deck.search (Deck.deck[11]); //search for 11th card in deck
//display the position
System.out.println("The Card is in position:" + Arrays.toString(pos));
虽然此代码返回了一个适当长度的数组,但它会用该值最后一次出现的位置填充每个槽。 (注意:我没有使用 ArrayList)
更新:在取出更新 y 的 for 循环并改为使 y 成为每次卡片匹配时更新的变量(在第二个循环中)后,问题已得到解决。
感谢大家提到 equals() 方法!
【问题讨论】:
-
尝试使用调试器
-
if (deck[x] == c)- 你的Card对象是否有一个被覆盖的equals方法?