在这里插入代码片
public class CardsDemo {
public static void main(String[] args) {
final int N = 52; //定义扑克的数量为常量
int poker[] = new int[N];//定义一个数组
String cardscolor[] = {"黑桃", "红星", "梅花", "方块"};//定义一个字符串,为牌面花色
String cardsface[] = {"A", "2", "3", "4", "5", "6", //定义一个字符串,为牌面数字
"7","8", "9", "10","J", "Q", "K"};
for (int i = 0; i < poker.length; i++) {
poker[i] = i;//定义扑克的牌面
}
System.out.println("洗牌前:");
for (int i = 0; i < poker.length; i++) {
System.out.printf("%s-%s", cardscolor[poker[i] / 13], cardsface[poker[i] % 13]);
/**
*i / 13 等于卡面的花色,花色只有4中,
*比13小的商为0所以花色是cardscolor[0]==黑桃,13-25商1,花色为cardcolor[1]==梅花
*26-38除13商2,所以花色是cardscolor[3]==梅花,39-52/13商3,等于cardscolor[3]==方块
*牌面判定规则,1%13等于1,所以牌面是A,2%13为2所以牌面是2....一直到12%13余数为12,所以牌面是K(数组是从0开始的,所以12对应K)
*然后13%13=0,cardsfaca[0]==A所有又开始循环...
*这样循环52次,定义每一张牌的花色和牌面
*/
if((i + 1) % 13 == 0){
/**
* 因为一开始打印了一个poker[i]所以需要i+1
* 当i==12的时候,i+1等于13,%13==0,
* 输出一个回车键,
* 代表打印13个poker[i]一个回车,
* 打印4行
* 否则就输出一个tab占位符
* 52/13==4
* 因为i从0开始,所以需要i加1
*/
System.out.print("\n");
}else
System.out.print("\t");
}
for (int i = 0; i < poker.length; i++) {
poker[i] = i;
}
for (int i = 0; i < poker.length; i++) {
int index = (int)(Math.random() * N);//0-51之间的随机数字 51 51 51 51 45 45 34 45 45 34 20 20 29
int temp = poker[i];//定义一个临时变量temp等于poker[i] 0 1 2 3 4 5 6 7 8 9 10 11 12
poker[i] = poker[index];//poker[i] 等于poker[随机数]51 0 1 2 45 4 34 5 7 6 20 10 29
poker[index] = temp;//poker[随机数]等于临时数0 1 2 3 4 5 6 7 8 9 10 11 12
}
System.out.print("洗牌后:\n");
for (int i = 0; i < poker.length; i++) {
System.out.printf("%s-%s", cardscolor[poker[i] / 13], cardsface[poker[i] % 13]);
if((i + 1) % 13 == 0){
System.out.print("\n");
}else
System.out.print("\t");
}
}
}
数组学习之洗牌
最新推荐文章于 2021-12-31 17:22:53 发布