我试图创造一副牌。卡组应该是一个数组,每张卡应该是一个对象
Card(int value, String name, int suit)
int值是卡的等级:2 = 2,Three = 3 ,. 。 。,杰克= 11
String名称是“Two”,“Three,..,”Ace“。
int诉讼可以是:0,1,2或3.其中0 =俱乐部,1 =钻石,2 =心,3 =黑桃
我知道如何创建Card对象。我遇到的问题是什么时候我应该创建Card [] deck数组。 显然我可以一次做一个:
Card[] deck = new Card[52];
deck[0] = new Card(2, "Two", 0); // Two of clubs, value = 2
deck[1] = new Card(3, "Three", 0); // Three of clubs, value = 3
但是用循环来做这件事会很好。但我无法做对..
答案 0 :(得分:0)
您需要首先创建一个数组,以使用其名称映射卡的值。
E.g。
String[] cardNames = new String[] {"", "", "Two", "Three", ...};
然后你可以使用嵌套循环。
Card[] deck = new Card[52];
int count = 0;
for(int i = 0; i < 4; i++) {
for(int j = 2; j < 15; j++) {
deck[count] = new Card(j, cardNames[j], i);
}
count++;
}
答案 1 :(得分:0)
试试这个(循环可以做得更好,但想给你一个想法),
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class CardExample {
public static void main(String[] args) {
Card[] deck = new Card[52];
Map<Integer, String> cardSeq = new HashMap<Integer, String>();
cardSeq.put(1, "Ace");
cardSeq.put(2, "Two");
cardSeq.put(3, "Three");
cardSeq.put(4, "Four");
cardSeq.put(5, "Five");
cardSeq.put(6, "Six");
cardSeq.put(7, "Seven");
cardSeq.put(8, "Eight");
cardSeq.put(9, "Nine");
cardSeq.put(10, "Ten");
cardSeq.put(11, "Jack");
cardSeq.put(12, "Queen");
cardSeq.put(13, "King");
int counter=0;
for (int i = 0; i <= 3; i++) {
Iterator<Map.Entry<Integer, String>> it = cardSeq.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, String> pair = it.next();
deck[counter]=new Card(pair.getKey(), pair.getValue(), i);
counter++;
}
}
for(Card c:deck){
System.out.println(c);
}
}
}
class Card {
private int value;
private String name;
private int suit;
Card(int value, String name, int suit) {
this.value = value;
this.name = name;
this.suit = suit;
}
@Override
public String toString() {
return "Card [value=" + value + ", name=" + name + ", suit=" + suit + "]";
}
}
答案 2 :(得分:0)
首先,实际上你没有必要明确存储排名(Ace,Two,Three ......),你可以创建一个方法,根据排名值返回排名。我会重新设计你的Card
课程,就像这样。
class Card {
private int suit, rank;
Card(int suit, int rank) {
this.suit = suit;
this.rank = rank;
}
public String getRankName() {
switch(rank)
{
case 11:
return "J";
case 12:
return "Q";
case 13:
return "K";
case 14:
return "A";
default:
return Integer.toString(rank);
}
}
//other getters, setters, methods....
}
接下来只需使用嵌套的for循环来创建Card
个对象
Card[] deck = new Card[52];
int index = 0;
for(int i = 0; i < 4; ++i) {
for(int j = 2; j < 15; ++j) {
deck[index] = new Card(i, j);
}
++index;
}