Java代码—-使用面向对象的思想描述扑克牌
详细代码
package edu.hunau.cxb19.oop.class07;
/**
*
* @author yf
*
* 2020-09-29 21:05:46
*/
public class Pocker {
/**
* 表示花色:每个扑克的实例都有自己的花色 0-黑桃♠ 1表示红桃♥ 2表示梅花♣ 3表示方块♦
*/
private int suit;
/**
* 使用常量描述花色:无论有多少扑克的实例 扑克的花色只有四种
*/
public static final int SUIT_HEITAO = 0;
public static final int SUIT_HONTAO = 1;
public static final int SUIT_MEIHUA = 2;
public static final int SUIT_FANGKUAI = 3;
public static final int SUIT_KING = 4;
public static final String[] SUIT_DESC = { "♠", "♥", "♣", "♦", "" };
/**
* 表示点数:每个扑克的实例都有自己的点数
*
*/
private int rank;
/**
* 使用常量描述点数:无论有多少扑克的实例,扑克的点数是可以穷举的
*/
public static final int RANK_3 = 0;
public static final int RANK_4 = 1;
public static final int RANK_5 = 2;
public static final int RANK_6 = 3;
public static final int RANK_7 = 4;
public static final int RANK_8 = 5;
public static final int RANK_9 = 6;
public static final int RANK_10 = 7;
public static final int RANK_J = 8;
public static final int RANK_Q = 9;
public static final int RANK_K = 10;
public static final int RANK_A = 11;
public static final int RANK_2 = 12;
public static final int RANK_XIAOWANG = 13;
public static final int RANK_DAWANG = 14;
public static final String[] RANK_DESC = { "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2", "小王",
"大王" };
// public String print() {
// return SUIT_DESC[this.suit] + RANK_DESC[this.rank];
// }
/**
* @param suit
* @param rank
*/
public Pocker(int suit, int rank) {
super();
this.suit = suit;
this.rank = rank;
}
/**
*
*/
public Pocker() {
super();
}
/**
* @return the suit
*/
public int getSuit() {
return suit;
}
/**
* @param suit the suit to set
*/
public void setSuit(int suit) {
this.suit = suit;
}
/**
* @return the rank
*/
public int getRank() {
return rank;
}
/**
* @param rank the rank to set
*/
public void setRank(int rank) {
this.rank = rank;
}
/**
* 重写toString方法 返回对象的内容
*/
@Override
public String toString() {
return SUIT_DESC[this.suit] + RANK_DESC[this.rank];
}
}
package edu.hunau.cxb19.oop.class07;
import org.junit.Test;
/**
*
* @author yf
*
* 2020-09-29 21:18:56
*/
public class PockerTest {
@Test
public void init() {
// 实例化梅花3
Pocker m3 = new Pocker(2, 0);
Pocker m4 = new Pocker(Pocker.SUIT_MEIHUA, Pocker.RANK_3);
System.out.println(m3.toString());// toString方法从Object继承
System.out.println(m4);// 直接输出对象 调用toString方法
}
/**
* 获得一副牌54张
*/
// @Test
public Pocker[] initPorks() {
Pocker[] pockers = new Pocker[54];
int index = 0;
for (int suit = 0; suit <= Pocker.SUIT_FANGKUAI; suit++) {
for (int rank = 0; rank <= Pocker.RANK_2; rank++) {
pockers[index++] = new Pocker(suit, rank);
}
}
pockers[index++] = new Pocker(Pocker.SUIT_KING, Pocker.RANK_XIAOWANG);
pockers[index++] = new Pocker(Pocker.SUIT_KING, Pocker.RANK_DAWANG);
return pockers;
}
@Test
public void showPockers() {
Pocker[] porks = initPorks();
for (int i = 0; i < porks.length; i++) {
System.out.print(porks[i] + " ");
if ((i + 1) % 13 == 0) {
System.out.println();
}
}
System.out.println();
}
}
控制台: