1. 若在应用程序的main方法中,定义字符串数组f和s:分别表示扑克牌的牌面值和花色;定义52个元素的Card类型数组deck,用来存放4个花色的52张牌。如下所示。
String f[]={“A”, “2”, “3”,
“4”, “5”, “6”, “7”, “8”,
“9”, “10”, “J”, “Q”, “K”};
String s[]=
{ “黑桃”, “红桃”, “梅花”, “方块”};
Card deck = new Card[ 52 ];Card 类源代码如下:class Card {
private String face;
private String suit;public Card(String f,String s) {
face = f;
suit = s;
}protected String getSuit(){
return suit;
}protected String getFace(){
return face;
}protected String toString(){
return face + “of”+suit;
}
}(1) 使用Card类的构造方法给deck数组的52张牌赋值,要求数组中先存放黑桃花色的A、2、3、……、K;然后是红桃花色的A、2、3、……、K;梅花花色的A、2、3、……、K;方块花色的A、2、3、……、K。请写出实现上述功能的程序段。
(2) 请编写模拟洗牌的程序段,即把数组deck中的扑克牌随机打乱存放顺序。
String f[]={“A”, “2”, “3”,
“4”, “5”, “6”, “7”, “8”,
“9”, “10”, “J”, “Q”, “K”};
String s[]=
{ “黑桃”, “红桃”, “梅花”, “方块”};
Card deck = new Card[ 52 ];Card 类源代码如下:class Card {
private String face;
private String suit;public Card(String f,String s) {
face = f;
suit = s;
}protected String getSuit(){
return suit;
}protected String getFace(){
return face;
}protected String toString(){
return face + “of”+suit;
}
}(1) 使用Card类的构造方法给deck数组的52张牌赋值,要求数组中先存放黑桃花色的A、2、3、……、K;然后是红桃花色的A、2、3、……、K;梅花花色的A、2、3、……、K;方块花色的A、2、3、……、K。请写出实现上述功能的程序段。
(2) 请编写模拟洗牌的程序段,即把数组deck中的扑克牌随机打乱存放顺序。
for (int j = 0; j < f.length; j++)
deck[i*f.length + j] = new Card(s[i], f[j]);
(2)Random rand = new Random(); // 随机数生成器,需import java.util.Randomfor (int i = 0; i < 52; i++) { // 取两个随机索引
int index1 = rand.nextInt(52);
int index2 = rand.nextInt(52); // 将两个索引位置上的元素对调
Card temp = deck[index1];
deck[index1] = deck[index2];
deck[index2] = temp;
}
card对象有3个属性
1、数字大小值(3-joker)0-13
2、种类大小值(方块、梅花...)值可以是0-3
3、表示字符(3,A.....)第二个就是在扑克数值里面随机抽数字咯,抽了删掉,再放到新的数组里
public class CardPlayer{
static String[] f = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
static String[] s = {"黑桃", "红桃", "梅花", "方块"};
static Card[] deck = new Card[52];
static int _p = 0;
static void exchangeCard(int a, int b){
Card temp;
temp = deck[a];
deck[a] = deck[b];
deck[b] = temp;
}
static void print(int n)
{
for (int i = 0; i < 52; i++){
System.out.println(deck[i].totheString());
}
}
public static void main(String[] args){
for (int i = 0; i < 4; i++)
for (int j = 0; j < 13; j++){
deck[i * 13 + j] = new Card(f[j], s[i]);
}
print(52); int n;
n = 10;//可以调整
for (int i = 1; i <= 10; i++){
Random r = new Random(++_p + System.nanoTime());
int a = r.nextInt(52);
int b = r.nextInt(52);
exchangeCard(a, b);
}
print(52);
}
}
class Card{
private String face;
private String suit;
public Card(String f, String s){
face = f;
suit = s;
}
protected String getSuit(){
return suit;
}
protected String getFace(){
return face;
}
protected String totheString(){
return face + "of" + suit;
}
}
TreeSet<Integer> ts = new TreeSet<Integer>();while(ts.size()<52) {
ts.add(rd.nextInt(52));
}
重新创建个Card数组,把deck的值按ts元素的顺序放入到新的数组里面