如何查找由字符串指定的花色的所有牌,例如“黑桃”在java中
我正在尝试找到所有相同花色的牌并将其归还。我已经尝试了一切,但我似乎没有做对。
public ArrayList<Card> findSuit(String suit) {
ArrayList<Card> cards = new ArrayList<Card>();
for(int i = 1; i <= pack.size(); i++){
cards.add(i);
}
return cards;
}
我收到的错误消息是:
ArrayList 类型中的方法 add(int, Card) 不适用于参数 (int)
I'm trying to find all the cards of same suit and return it. I've tried everything but I don't seem to get it right.
public ArrayList<Card> findSuit(String suit) {
ArrayList<Card> cards = new ArrayList<Card>();
for(int i = 1; i <= pack.size(); i++){
cards.add(i);
}
return cards;
}
The error message that I'm getting is:
The method add(int, Card) in the type ArrayList is not applicable for the arguments (int)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
首先,集合中的索引从0开始,以size()-1结束。
我假设类卡有属性套装。所以代码:
First of all, indexes in collections start from 0 and ends in size()-1.
I assume that the class Card has a property suit. So the code:
假设
pack
定义为List
或ArrayList
pack
在函数内部可见Card
类有一个名为getSuit()
的方法,以字符串形式返回西装,那么下面的代码就可以工作。
将 == 更改为
equals
(我通常使用枚举来处理这种事情)。Assuming that
pack
is defined as aList<Card>
orArrayList<Card>
pack
is visible inside the functionCard
class has a method namedgetSuit()
returning the suit as a Stringthen the following will work.
Changed == to
equals
(i usually use enums for this kind of thing).您需要
add()
对正确类的对象的引用,在本例中为Card
。在不查看类定义的情况下很难知道如何创建这样的对象,但如果有一个来自整数的构造函数,也许cards.add(new Card(i))
可以工作。You need to
add()
a reference to an object of the proper class,Card
in this case. It's hard to know how to create such an object without seeing the class definition, but perhapscards.add(new Card(i))
works, if there is a constructor from an integer.您需要将卡对象(例如
Card
类)添加到数组列表中,该数组列表由add()
的第二个参数例如,如果 然后你
就可以:
当然,你需要通过 Card 类构造函数实际创建
Card
对象,以便可以添加它们。You need to add a card object (e.g. of class
Card
) to an arraylist, which is specified by a second argument toadd()
E.g. if you have
Then you do:
Of course, you need to actually create the
Card
object via Card class constructor so they can be added..Add 采用一个索引 (int) 和一个元素(Object 类型)。
您仅指定 int。
请参阅文档以获取说明和示例:
http://download.oracle .com/javase/1.4.2/docs/api/java/util/ArrayList.html#add(int, java.lang.Object)
.Add takes an index (int) and an element (of type Object).
You are only specifying int.
See the documents for a description and examples:
http://download.oracle.com/javase/1.4.2/docs/api/java/util/ArrayList.html#add(int, java.lang.Object)