数组学习之洗牌

在这里插入代码片
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");
		}
	}
}	


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值